Search code examples
classswiftdrawingnsview

Drawing a line on NSView in swift


That's my code at the moment:

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
}
}

And I just don't have any ideas how to draw the line with a selected color (e.g. black) for each line in line array. I'm new to swift, so I'll be grateful for the comprehensive explanation.


Solution

  • Like this:

    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
      }
    }
    

    I guess this is mostly self explaining. The coordinates are that which you use inside the view's frame.

    If the lines are not updating then you need

    view.needsDisplay = true
    

    in your viewController. Put in a println to see that the view is actually re-drawn.