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 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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With