【问题标题】:How can I reset CABasicAnimation?如何重置 CABasicAnimation?
【发布时间】:2015-03-08 00:12:13
【问题描述】:

我正在尝试制作一个圆圈并为其设置动画。当我点击按钮时,我想从同一个起点重新开始这个动画。当我单击按钮时,我应该停止,清除图像并重新启动。 我正在尝试使用下面的代码,但它不起作用。

-(IBAction)MakeCircle:(id)sender{

    // Make a circular shape
    CAShapeLayer *circle = [CAShapeLayer layer];    
    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
                                            cornerRadius:radius].CGPath;

    // Positioning
    circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
                                  CGRectGetMidY(self.view.frame)-radius);

    // Configure color and linewidth
    circle.fillColor = [UIColor whiteColor].CGColor;
    circle.lineWidth = 10;

     // Add to parent layer
    [self.view.layer addSublayer:circle];

    // Configure animation
    //CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = 5.0; 
    drawAnimation.repeatCount         = 1.0; 
    drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    drawAnimation.toValue   = [NSNumber numberWithFloat:1.0f];
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    // Add the animation
    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];


}

//Stop, "clean"screen and start again

-(IBAction)ButtonStopClearStart:(id)sender{

    circle.speed = 0.0;
    [circle removeAnimationForKey:@"drawCircleAnimation"];
    [self MakeCircle:(sender)];
}

【问题讨论】:

  • 不是每次都为每个动画创建 CAShapeLayer,而是在 viewDidLoad 中创建一次,然后像你一样简单地将动画添加到它。当在你计划的动画上指定 fromValue 时,它​​将重置动画并重新开始。
  • 现在我遇到了同样的问题。
  • 但我无法理解@Andy 的建议,如果能发布详细的答案就好了:(

标签: ios objective-c cabasicanimation


【解决方案1】:

假设您的动画看起来像这样......

func runTimerMaskAnimation(duration: CFTimeInterval, fromValue : Double){

       ...
             let path = UIBezierPath(roundedRect: circleBounds, cornerRadius: 
             circleBounds.size.width * 0.5)
             maskLayer?.path = path.reversing().cgPath
             maskLayer?.strokeEnd = 0
    
             parentCALayer.mask = maskLayer
    
             let animation = CABasicAnimation(keyPath: "strokeEnd")
             animation.duration = duration
             animation.fromValue = fromValue
             animation.toValue = 0.0
             maskLayer?.add(animation!, forKey: "strokeEnd")
}

如果我想从原始位置重新启动计时器,我会移除动画,移除 maskLayer,然后再次运行动画。

 maskLayer?.removeAnimation(forKey: "strokeEnd")
 maskLayer?.removeFromSuperlayer()
 runTimerMaskAnimation(duration: 15, fromValue : 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多