我正在尝试动画一段圆圈的外观。为了存档这个我使用CABasicAnimations工作安静。
动画从顶部开始,很好地安静地移动到整个圆圈的三分之一。但是当动画结束时,圆圈会立即完全绘制。
我该怎样防止这种情况?
以下是我的自定义UIView的源代码:
- (void)drawRect:(CGRect)rect
{
int radius = 100;
int strokeWidth = 10;
CGColorRef color = [UIColor redColor].CGColor;
int timeInSeconds = 5;
CGFloat startAngle = 0;
CGFloat endAngle = 0.33;
CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
circle.position = CGPointMake(CGRectGetMidX(self.frame)-radius, CGRectGetMidY(self.frame)-radius);
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = color;
circle.lineWidth = strokeWidth;
[self.layer addSublayer:circle];
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration = timeInSeconds;
drawAnimation.repeatCount = 1.0;
drawAnimation.removedOnCompletion = NO;
drawAnimation.fromValue = [NSNumber numberWithFloat:startAngle];
drawAnimation.toValue = [NSNumber numberWithFloat:endAngle];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
}
答案 0 :(得分:18)
将动画应用于图层时,Core Animation会创建图层的副本并为副本的属性设置动画。原始图层称为模型图层,副本称为表示图层。动画永远不会更改模型图层的属性。
您尝试通过将removedOnCompletion
设置为NO
来解决此问题。您还必须设置动画的fillMode
才能使其正常工作,但这并不是动画属性的正确方法。
正确的方法是更改模型图层上的属性,然后应用动画。
// Change the model layer's property first.
circle.strokeEnd = endAngle;
// Then apply the animation.
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration = timeInSeconds;
drawAnimation.fromValue = [NSNumber numberWithFloat:startAngle];
drawAnimation.toValue = [NSNumber numberWithFloat:endAngle];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
Core Animation Essentials video中的WWDC 2011对此进行了解释。我强烈推荐观看它。