【发布时间】:2021-06-22 00:22:41
【问题描述】:
当鼠标按下事件开始时,我正在绘制一个形状,并且该动画是在鼠标拖动事件上绘制的。下面是使用的代码:
override func mouseDown(with event: NSEvent) {
self.startPoint = self.convert(event.locationInWindow, from: nil)
if self.shapeLayer != nil {
self.shapeLayer.removeFromSuperlayer()
self.shapeLayer = nil
}
var pixelColor: NSColor = NSReadPixel(startPoint) ?? NSColor()
shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = NSColor.clear.cgColor
if pixelColor == NSColor.black {
pixelColor = NSColor.color_white
} else {
pixelColor = NSColor.black
}
shapeLayer.strokeColor = pixelColor.cgColor
shapeLayer.lineDashPattern = [1]
self.layer?.addSublayer(shapeLayer)
var dashAnimation = CABasicAnimation()
dashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
dashAnimation.duration = 0.75
dashAnimation.fromValue = 0.0
dashAnimation.toValue = 15.0
dashAnimation.repeatCount = 0.0
shapeLayer.add(dashAnimation, forKey: "linePhase")
}
override func mouseDragged(with event: NSEvent) {
let point: NSPoint = self.convert(event.locationInWindow, from: nil)
let path = CGMutablePath()
path.move(to: self.startPoint)
path.addLine(to: NSPoint(x: self.startPoint.x, y: point.y))
path.addLine(to: point)
path.addLine(to: NSPoint(x: point.x, y: self.startPoint.y))
path.closeSubpath()
self.shapeLayer.path = path
}
目前它也会像这样绘制矩形:
我们能不能把它绑定成方形,这样当用户开始拖动鼠标时,它就会一直跟随方形?
【问题讨论】:
标签: ios swift macos crop nsimage