簡體   English   中英

如何在Core Animation中平滑更新動畫的toValue /終點?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM