在swift中从中心拖出一条线,使其跳转

时间:2018-02-19 13:30:36

标签: swift math uikit

我正在尝试创建一个能够在任何视图中绘制的LineSegment结构,并且我还想用Pan手势识别器更改其值。

我做到了,它有效,但是当我试图将它从中心拖出时它跳了起来。



<div class="cloudapp-embed" data-slug="1V3q0s420Q2t"><script async src="https://embed.cl.ly/embedded.gz.js" charset="utf-8"></script></div>
&#13;
&#13;
&#13;

public struct LineSegment {

var a: CGPoint!
var b: CGPoint!

var center: CGPoint! {
    get {
        let centerDistance = a.distance(to: b) / 2
        return getPointOnLineWithDistaceFromA(centerDistance)
    }
    set (newCenter) {
        let axOffset = newCenter.x - a.x
        let ayOffset = newCenter.y - a.y
        let bxOffset = newCenter.x - b.x
        let byOffset = newCenter.y - b.y
        let newa = CGPoint(x: newCenter.x + axOffset, y: newCenter.y + ayOffset)
        let newb = CGPoint(x: newCenter.x + bxOffset, y: newCenter.y + byOffset)
        self.a = newa
        self.b = newb
    }
}

var shapeLayer: CAShapeLayer? = nil
var dragRadius: CGFloat = 30

init(a: CGPoint, b:CGPoint) {
    self.a = a
    self.b = b
}
}
extension LineSegment {

func getPointOnLineWithDistaceFromA(_ distance: CGFloat) -> CGPoint {
    let d = a.distance(to: b)
    let t = distance / d
    let newP = CGPoint(x: (1 - t) * a.x + t * b.x, y: (1 - t) * a.y + t * b.y)
    return newP
}

/// Grabs the closes point and moves it to 'to'
mutating func grabClosestPoint(to: CGPoint, grabCenter: Bool = false) {
    if to.distance(to: a) < self.dragRadius {
        self.a = to
    } else if to.distance(to: b) < self.dragRadius {
        self.b = to
    } else if grabCenter && to.distance(to: self.center) < self.dragRadius {
        self.center = to
    }
}
}

我打电话给#34; grabClos​​estPoint&#34;功能与panGesture。

我不知道是什么问题,数学是错误的,或者有一些我无法弄清楚的UI问题...

2 个答案:

答案 0 :(得分:0)

我想出来了。数学错了。

let axOffset = newCenter.x - a.x
let ayOffset = newCenter.y - a.y
let bxOffset = newCenter.x - b.x
let byOffset = newCenter.y - b.y
let newa = CGPoint(x: newCenter.x + axOffset, y: newCenter.y + ayOffset)
let newb = CGPoint(x: newCenter.x + bxOffset, y: newCenter.y + byOffset)
self.a = newa
self.b = newb

这不仅可以翻译边缘,还可以翻转它们。所以我将其更改为:

 let centerOffsetX = newCenter.x - self.center.x
 let centerOffsetY = newCenter.y - self.center.y
 let newa = CGPoint(x: a.x + centerOffsetX, y: a.y + centerOffsetY)
 let newb = CGPoint(x: b.x + centerOffsetX, y: b.y + centerOffsetY)
 self.a = newa
 self.b = newb

现在效果很好。

答案 1 :(得分:-1)

问题是您没有在任何地方声明距离变量,所以它破坏了代码