目前,我正在使用以下代码在NSView
支持的图层上绘制形状。假设形状是简单填充的rect
-因为我还没有包括形状绘制代码。
我可以通过响应鼠标拖动事件而调用offsetSelectedItems()
方法来对要拖动的形状进行动画处理,
每个对象都存储在一个类中,该类具有其绘图代码使用的location和angle属性。
我现在尝试在没有鼠标输入以响应其他用户更改对象位置的情况下为移动创建动画-当对象的位置和/或角度更改时,对象会收到通知。
发生这种情况时,我想将运动设置为新的位置/角度-我想我可以创建自己的线程来反复调用offsetSelectedItems()
-但是我想知道是否可以使用Core Animation来实现更好的效果结果。
如果可以的话,我也想避免创建CAShapeLayer-也许从长远角度来看,这是正确的做法,但这将需要更多调查和附加代码来管理子视图。
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
guard let context = NSGraphicsContext.current?.cgContext else {
return
}
context.setFillColor(NSColor.clear.cgColor)
context.fill(dirtyRect)
for item in draggableItems {
if NSIntersectsRect(dirtyRect, item.bounds(scale)) {
item.draw(scale)
}
}
}
func offsetSelectedItemsLocationBy(x: CGFloat, y:CGFloat)
{
// since the offset can be generated by both mouse moves
// and moveUp:, moveDown:, etc.. actions, we'll invert
// the deltaY amount based on if the view is flipped or
// not.
let invertDeltaY: CGFloat = self.isFlipped ? -1.0: 1.0
let y1=y*invertDeltaY
for item in draggableItems {
if item.isSelected {
// Check if item will go outside of bounds
let point = NSPoint(x: item.location.x*scale+x/scale, y: item.location.y*scale+y1/scale)
if NSPointInRect(point, self.frame) {
self.setNeedsDisplay(item.bounds(scale))
item.offsetLocationBy(x: x/scale, y: y1/scale)
// invalidate the new rect location so that it'll
// be redrawn
self.setNeedsDisplay(item.bounds(scale))
}
}
}
}