【问题标题】:Why when I add my animation with Core Animation does it immediately snap back to what it was at the end? [duplicate]为什么当我使用 Core Animation 添加动画时,它会立即恢复到最后的状态? [复制]
【发布时间】:2014-04-22 02:04:26
【问题描述】:

我正在尝试构建一个简单的饼图样式进度指示器。它的动画效果很好,但是在动画结束后,它会立即恢复到动画之前的上一个值。

我的代码如下:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    // Create a white ring that fills the entire frame and is 2 points wide.
    // Its frame is inset 1 point to fit for the 2 point stroke width
    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;

    // Create a white pie-chart-like shape inside the white ring (above).
    // The outside of the shape should be inside the ring, therefore the
    // frame needs to be inset radius/2 (for its outside to be on
    // the outside of the ring) + 2 (to be 2 points in).
    self.innerPie = [CAShapeLayer layer];
    inset = radius/2; // The inset is updated here
    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 {
    self.innerPie.hidden = NO;

    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    pathAnimation.duration = 3.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:_progress];
    pathAnimation.toValue = [NSNumber numberWithFloat:progress];
    [self.innerPie addAnimation:pathAnimation forKey:@"strokeEndAnimation"];

    if (_progress != progress) {
        _progress = progress;
    }
}

我只是在drawRect 中设置它然后有一个方法来设置动画进度。我在这里做错了什么?

【问题讨论】:

    标签: ios objective-c cocoa-touch core-animation


    【解决方案1】:

    这就是核心动画的工作原理。您要做的是在将动画添加到图层之前将属性设置为其最终值。然后动画隐藏了你更改了属性的事实,当动画完成后被移除时,属性处于它的结束值。

    【讨论】:

    • 在这种情况下我会设置什么属性?
    • 在这种情况下,它将是 strokeEnd 属性 - 请参阅此问题 - stackoverflow.com/questions/16326623/…
    • 正如@Paulw11 所说,对于您上面的代码,它是图层的 strokeEnd 属性。更一般地说,它是您在创建动画时指定的使用 animationWithKeyPath: 键路径修改的任何属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2013-10-03
    相关资源
    最近更新 更多