gpt4 book ai didi

swift - cocoa swift上用鼠标简单画图

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:47 34 4
gpt4 key购买 nike

我找不到任何用鼠标在 View 上绘制的简单解决方案。全部tutorials使用 NSBezierPath 绘制线条、矩形等。但我需要一个简单的应用程序,使用鼠标进行绘图,如下所示: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()
}

请建议我如何绘制单点

最佳答案

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

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

关于swift - cocoa swift上用鼠标简单画图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47738822/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com