在swift中在NSView上画一条线

时间:2015-01-30 13:31:37

标签: class swift drawing nsview

这是我目前的代码:

class LineDrawer : NSView {
required init?(coder  aDecoder : NSCoder) {
    super.init(coder: aDecoder)
}

var line : Array<Line> = []
var lastPt : CGPoint!

override func mouseDown(theEvent: NSEvent) {
    super.mouseDown(theEvent)
    let location = theEvent.locationInWindow
    println(location)

}
override func mouseDragged(theEvent: NSEvent) {
    super.mouseDragged(theEvent)
    var newPt = theEvent.locationInWindow
    line.append(Line(start: newPt, end: lastPt))
    lastPt = newPt
}
override func drawRect(dirtyRect: NSRect) {

}
}

class Line {
var start : CGPoint
var end : CGPoint
init(start _start : CGPoint, end _end : CGPoint) {
    start = _start
    end = _end
}
}

我只是没有任何想法如何为线阵列中的每一行绘制具有所选颜色(例如黑色)的线。我是新手,所以我会感激全面的解释。

2 个答案:

答案 0 :(得分:5)

像这样:

class SomeView:NSView {

  override func drawRect(dirtyRect: NSRect) {
    NSColor.redColor().set() // choose color
    let figure = NSBezierPath() // container for line(s)
    figure.moveToPoint(NSMakePoint(x, y)) // start point
    figure.lineToPoint(NSMakePoint(x+10.0, y+10.0)) // destination
    figure.lineWidth = 1  // hair line
    figure.stroke()  // draw line(s) in color
  }
}

我想这主要是自我解释。坐标是您在视图框架内使用的坐标。

如果这些行没有更新,那么你需要

view.needsDisplay = true
在viewController中

。放入println以查看视图是否实际重新绘制。

答案 1 :(得分:0)

对于Swift 5+和MacOS:

override func draw(_ dirtyRect: NSRect) {
    NSColor.red.set()
    let figure = NSBezierPath()
    figure.move(to: NSMakePoint(100, 100)) // {x,y} start point
    figure.line(to: NSMakePoint(110.0, 120.0)) //  {x,y} destination
    figure.lineWidth = 1  // hair line
    figure.stroke()  // draw line
}