Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 316
pomo_mondreganto Avatar asked Jan 30 '15 13:01

pomo_mondreganto


2 Answers

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.

like image 173
qwerty_so Avatar answered Oct 04 '22 13:10

qwerty_so


For swift 5+ and 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
}
like image 32
HCarrasko Avatar answered Oct 04 '22 11:10

HCarrasko