swift – 同时移动所有矩形点

我正在为应用程序构建矩形编写代码.我可以用鼠标左键(LMB)单独移动矩形点.

我怎样才能同时移动矩形的所有四个点?

操作原理:如果我用LMB拖动1个点,其他3个将同时跟随它并具有相同的偏移量.

《swift – 同时移动所有矩形点》

这就是构造元素的方式:

enum RectPoint {

    case point1(point: CGPoint)
    case point2(point: CGPoint)
    case point3(point: CGPoint)
    case point4(point: CGPoint)

    func pointCoord() -> [CGPoint] {    
        switch self {  
        case .point1(let point): return [point]
        case .point2(let point): return [point]
        case .point3(let point): return [point]
        case .point4(let point): return [point]
        }
    }
    ..........................
    ..........................
}

class SpecialView: NSView {

    var array: [RectPoint] = [] 
    private var trackVertex: RectPoint?
    private var trackVertexIndex: Int?
    private var trackElementIndex: Int?

    ..........................
    ..........................

    private func updateDragging(point: CGPoint) {
        guard let trackVertex = self.trackVertex,
        let trackVertexIndex = self.trackVertexIndex,
        let trackElementIndex = self.trackElementIndex   
        else { 
            return 
        }

        let newVertex = trackVertex.debugReleaseChecking(point, 
            atElementIndex: trackElementIndex)

        array[trackVertexIndex] = newVertex     
        self.needsDisplay = true
    }
}

这是使用LMB拖动的方法:

func mouseDragged(event: NSEvent) {

   var point = self.convertPoint(event.locationInWindow, fromView: nil)

       updateDragging(point) 
}

我需要一个代码(或伪代码),允许我一次拖动任何矩形的所有四个点.

最佳答案 基本上,您需要计算应用于跟踪点的偏移量,并将该偏移量应用于所有其他点.最简单的方法是通过分离计算和更新来完成此操作,因此更新始终在所有点上运行.

要计算偏移量,只需从新点x和y中减去当前点x和y.

有点像:

func mouseDragged(event: NSEvent) {
    let eventPoint = self.convertPoint(event.locationInWindow, fromView: nil)
    let trackingPoint = XXX

    let xOffset = eventPoint.x - trackingPoint.x
    let yOffset = eventPoint.y - trackingPoint.y

    for point in allPoints {
        point.x += xOffset
        point.y += yOffset
    }
}
点赞