Home:ALL Converter>How to code drawing a straight line with two mouse clicks (OSX Mac App)?

How to code drawing a straight line with two mouse clicks (OSX Mac App)?

Ask Time:2016-07-06T18:41:38         Author:sundrius

Json Formatter

I'm trying to make a simple drawing app (OSX Mac app) and I'm trying to figure out how the user can draw a line by two mouse clicks, for example, the first mouse click (mouseDown then mouseUP) would mark the origin point of the line, and the second mouse click (mouseDown then mouseUP) would mark the end point of the line. Before the user makes the second click of the end point, I'd like the line (before anchoring the end point) to be shown live, kind of like in photoshop. Both Objective-C and Swift are fine.

So far I've got...

var newLinear = NSBezierPath()

override func mouseDown(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        var lastPoint = theEvent.locationInWindow
        lastPoint.x -= frame.origin.x
        lastPoint.y -= frame.origin.y
        newLinear.moveToPoint(lastPoint)
    }

override func mouseUp(theEvent: NSEvent) {
        var newPoint = theEvent.locationInWindow
        newPoint.x -= frame.origin.x
        newPoint.y -= frame.origin.y
        newLinear.lineToPoint(newPoint)
        needsDisplay = true
    }

Cheers!

Author:sundrius,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38222054/how-to-code-drawing-a-straight-line-with-two-mouse-clicks-osx-mac-app
andyvn22 :

enums with associated values are great for this as your application scales up and possibly adds other tools and states.\n\nenum State {\n case normal\n case drawingLine(from: CGPoint, to: CGPoint)\n}\nvar state = State.normal\n\noverride func mouseDown(theEvent: NSEvent) {\n super.mouseDown(theEvent)\n var lastPoint = theEvent.locationInWindow\n lastPoint.x -= frame.origin.x\n lastPoint.y -= frame.origin.y\n state = .drawingLine(from: lastPoint, to: lastPoint)\n}\n\noverride func mouseUp(theEvent: NSEvent) {\n if case .drawingLine(let firstPoint, _) = state {\n var newPoint = theEvent.locationInWindow\n newPoint.x -= frame.origin.x\n newPoint.y -= frame.origin.y\n //finalize line from `firstPoint` to `newPoint`\n }\n}\n\noverride func mouseMoved(theEvent: NSEvent) {\n if case .drawingLine(let firstPoint, _) = state {\n needsDisplay = true\n var newPoint = theEvent.locationInWindow\n newPoint.x -= frame.origin.x\n newPoint.y -= frame.origin.y\n state = .drawingLine(from: firstPoint, to: newPoint)\n }\n}\n\noverride func draw(_ dirtyRect: NSRect) {\n if case .drawingLine(let firstPoint, let secondPoint) = state {\n //draw your line from `firstPoint` to `secondPoint`\n }\n}\n",
2016-07-07T09:28:15
yy