7

円のセグメントの外観をアニメーション化しようとしています。これをアーカイブするために、私は静かにうまく機能するCABasicAnimationsを使用します。

アニメーションは上から始まり、円全体の3分の1まで静かに移動します。しかし、アニメーションが終了すると、すぐに円が完全に描画されます。

どうすればそれを防ぐことができますか?

カスタム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"];
}
4

1 に答える 1

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"];

これは、WWDC 2011のCore Animation Essentialsビデオで説明されています。見ることを強くお勧めします。

于 2012-02-04T18:08:36.323 に答える