Animate a line using CALayer in NSView
I have a custom subclass of NSView in which I draw a horizontal line. My NSView has a property called lineLength
that defines the length of the line.
I would like to trigger an animation that makes the line grow. I use any mouse click on the view as trigger (not mandatory, just a simple way to start the animation).
Well, it doesn't work. My line doesn't even draw since I added the CA Layer and I don not understand what's happening. Clearly, I missed something.
What should I do to animate my line ?
class myView: NSView
{
var lineLength: CGFloat = 10.0
override func awakeFromNib()
{
super.awakeFromNib()
self.layer = CALayer()
self.wantsLayer = true
self.layer?.display()
}
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
// Drawing code here.
let path = NSBezierPath()
path.moveToPoint(NSMakePoint(0.0, 10.0)
path.lineToPoint(NSMakePoint(lineLength, 10.0)
NSColor.blackColor().set()
path.stroke()
}
override func mouseDown(theEvent: NSEvent)
{
let animation:CABasicAnimation = CABasicAnimation()
animation.keyPath = "lineLength";
animation.fromValue = 10;
animation.toValue = 500;
animation.duration = 3;
self.layer!.addAnimation(animation, forKey: "basic");
}
}
One idea, would be to subclass the CALayer and use it to draw. But I don't think I'm supposed to do that. Usually, apple as simpler solutions.
You can make the line a variable of your myView
- a CAShapeLayer. Add it as a sublayer of your view's layer.
var yourLineLayer = CAShapeLayer()
// then in your awake..
layer.addSublayer(yourLineLayer)
Your drawing code for the line will be a little different too. You can create the path as you're doing, but then use that path to set up the shape layer.
yourLineLayer.path = path.CGPath()
yourLineLayer.strokeColor = UIColor.blackColor()
yourLineLayer.fillColor = UIColor.clearColor()
You can add animations to that CAShapeLayer. Also your animation doesn't really do anything. Here's what it would look like to animate the line.
override func mouseDown(theEvent: NSEvent)
{
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = 3
yourLineLayer.addAnimation(animation, forKey: "strokeEnd")
}
链接地址: http://www.djcxy.com/p/74202.html