![](/img/trans.png)
[英]How can I change toValue/fromValue of CABasicAnimation while the animation is on
[英]How do I smoothly update the toValue/end point of an animation in Core Animation?
我试图模仿苹果在iOS 7中下载应用程序时作为进度指示器的效果,有点像饼图:
我的代码进展顺利。 我可以给它一个值,它将更新为该值。
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGFloat radius = CGRectGetWidth(self.frame) / 2;
CGFloat inset = 1;
CAShapeLayer *ring = [CAShapeLayer layer];
ring.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)cornerRadius:radius-inset].CGPath;
ring.fillColor = [UIColor clearColor].CGColor;
ring.strokeColor = [UIColor whiteColor].CGColor;
ring.lineWidth = 2;
self.innerPie = [CAShapeLayer layer];
inset = radius/2;
self.innerPie.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
cornerRadius:radius-inset].CGPath;
self.innerPie.fillColor = [UIColor clearColor].CGColor;
self.innerPie.strokeColor = [UIColor whiteColor].CGColor;
self.innerPie.lineWidth = (radius-inset)*2;
[self.layer addSublayer:ring];
[self.layer addSublayer:self.innerPie];
self.progress = 0.0;
self.innerPie.hidden = YES;
}
- (void)setProgress:(CGFloat)progress animated:(BOOL)animated {
if (animated) {
self.innerPie.hidden = NO;
self.innerPie.strokeEnd = progress;
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
pathAnimation.duration = 0.5;
pathAnimation.fromValue = [NSNumber numberWithFloat:self.progress];
pathAnimation.toValue = [NSNumber numberWithFloat:progress];
[self.innerPie addAnimation:pathAnimation forKey:@"strokeEnd"];
}
else {
[CATransaction setDisableActions:YES];
[CATransaction begin];
self.innerPie.hidden = NO;
self.innerPie.strokeEnd = progress;
[CATransaction commit];
}
self.progress = progress;
}
我的问题在于在动画过程中更新进度 。 例如,如果我正在下载文件,并且进度从0.1跳到0.2(从10%跳到20%),则我想对此进行动画处理。 假设我给了它0.5秒的动画。 如果在0.5秒的动画中0.2秒跳到0.4(40%),该怎么办?
使用我当前的代码,它会跳到第一个动画(20%)中应该结束的位置(应该动画时),然后再次朝40%的方向动画。
我想要的是将它的toValue
几乎更新为0.4。 至少那是我想要的。 从概念上讲,我希望它在不中断先前值的情况下朝新值继续动画。 简单地说,就是平滑度。
我将如何完成?
我知道有图书馆可以做到这一点。 我想自己做,以学习为目的。
你应该更换
pathAnimation.fromValue = [NSNumber numberWithFloat:self.progress];
与:
pathAnimation.fromValue = [NSNumber numberWithFloat:[self.innerPie.presentationLayer strokeEnd]];
最初, [self.innerPie.presentationLayer strokeEnd]]
将为1,因此您需要将初始值设置为0。将这两行添加到创建“ innerPie”的位置:
self.innerPie.strokeStart = 0;
self.innerPie.strokeEnd = 0;
我已经测试过并且可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.