用可可快速的鼠标简单绘图

时间:2017-12-10 12:26:56

标签: swift macos cocoa

我找不到用鼠标在视图上绘制的任何简单解决方案。所有tutorials使用NSBezierPath绘制线条,rects等。但我需要使用鼠标这样的简单应用绘图:http://juliuspaintings.co.uk/cgi-bin/paint_css/animatedPaint/010-NSView.pl

我试图转换它。但是没有什么对我有用:

var lastPoint = NSZeroPoint
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var swiped = false

override func mouseUp(with event: NSEvent) {
        if !swiped {
            drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
        }

    }

    override func mouseDragged(with event: NSEvent) {
        swiped = true
        let currentPoint = event.locationInWindow
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }


    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
        print("drag")
        var ctx = NSGraphicsContext.current
        ctx?.cgContext.setStrokeColor(CGColor(red: 255, green: 0, blue: 0, alpha: 1.0))
        ctx?.cgContext.setLineWidth(5.0)
        ctx?.cgContext.beginPath()
        ctx?.cgContext.move(to: fromPoint)
        ctx?.cgContext.addLine(to: toPoint)
        ctx?.cgContext.drawPath(using: .fillStroke)
        ctx?.cgContext.closePath()
    }

请建议我如何画单点

1 个答案:

答案 0 :(得分:5)

我创建了一个简单的演示,可以用鼠标事件绘制一些东西。如果您想要颜色或线宽等,可以更改任何参数。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    let view = DrawView()
    view.translatesAutoresizingMaskIntoConstraints = false
    self.window.contentView?.addSubview(view)

    self.window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": view]))
    self.window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": view]))
}

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
}

}

class DrawView: NSView {
var path: NSBezierPath = NSBezierPath()

override func mouseDown(with event: NSEvent) {
    path.move(to: convert(event.locationInWindow, from: nil))
    needsDisplay = true
}

override func mouseDragged(with event: NSEvent) {
    path.line(to: convert(event.locationInWindow, from: nil))
    needsDisplay = true
}

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    NSColor.black.set()

    path.lineJoinStyle = .roundLineJoinStyle
    path.lineCapStyle = .roundLineCapStyle
    path.lineWidth = 10.0
    path.stroke()
}
}

enter image description here