在两个物体之间画一条线

时间:2019-05-02 19:53:58

标签: swift cocoa drawing

我尝试编写一个简单的应用程序在它们之间绘制顶点和边缘。我成功编写了添加顶点,删除顶点并在视图中拖动的代码。但是,当我试图在两者之间划清界限时,我遇到了问题。许多关于此的指南已与旧版本的Swift或有关IOS开发的过时了,所以我没有找到实现的方法。

我试图在点之间画一条线,但是没有任何效果,还注意到我想在拖动顶点时更改边的坐标。

import Cocoa

var merging = false
var mergingCoords:[CGPoint] = []

class Vertex {
    var number:Int

    init(number: Int) {
        self.number = number
    }

}

class Graph {
    var size = 0
}

class VertexView: NSBox {

    var point: CGPoint = CGPoint(x: 0, y: 0)

    required init(coder decoder: NSCoder) {
        super.init(coder: decoder)!
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    override func mouseDown(with event: NSEvent) {
        if (merging) {
            print("Really")
            mergingCoords.append(self.point)
            if (mergingCoords.count == 2) {
                // DRAW AN EDGE
            }
        } else {
            point = event.locationInWindow
        }
    }

    override func mouseUp(with event: NSEvent) {
        if (!merging) {
            if (event.locationInWindow == point) {
                self.removeFromSuperview()
            } else {
                point = event.locationInWindow
            }
        }
    }

    override func mouseDragged(with event: NSEvent) {
        if (!merging) {
            self.frame = NSRect(x: event.locationInWindow.x - 20, y: event.locationInWindow.y - 20, width: 40, height: 40)
        }
    }

}

class ViewController: NSViewController {

    var graph: Graph = Graph()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func viewDidAppear() {
        view.window?.makeFirstResponder(self)
    }

    override func keyDown(with event: NSEvent) {
        print(event.characters!)
        if (event.characters! == "M") {
            merging = !merging;
            mergingCoords.removeAll()
        }
        print(merging)
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func mouseDown(with event: NSEvent) {
        let v = VertexView(frame: NSRect(x: event.locationInWindow.x - 20, y: event.locationInWindow.y - 20, width: 40, height: 40))
        v.boxType = NSBox.BoxType.custom
        v.point = event.locationInWindow
        v.cornerRadius = 20
        graph.size = graph.size + 1
        self.view.addSubview(v)
    }

}

0 个答案:

没有答案