我有一个动画片,它是一个按照计时器在屏幕上移动的动画,每次敲击时都会缩短。我的问题是动画只播放一次。我尝试调用动画重置并再次开始吧,但没有任何反应。这是一些代码:
-(IBAction)targetTapped:(id)sender {
[Time invalidate];
targX = arc4random() %619;
targY = arc4random() %925;
NSLog([NSString stringWithFormat:@"X = %li", (long)targX]);
NSLog([NSString stringWithFormat:@"Y = %li", (long)targY]);
Target.center = CGPointMake(targX, targY);
Score = Score + 1;
if (Score >= 225) {
timeMax = 0.5;
}
else {
timeMax = 5 - (Score * 0.02);
}
Time = [NSTimer scheduledTimerWithTimeInterval:timeMax target:self selector:@selector(Lose) userInfo:nil repeats:NO];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0,895.0)];
[path addLineToPoint:CGPointMake(768.0, 895.0)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor blueColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 5.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.view.layer addSublayer:pathLayer];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = timeMax;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer animationForKey:@"strokeEnd"];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
答案 0 :(得分:1)
您可以创建一次pathLayer:
[self.pathLayer removeAnimationForKey:@"strokeEnd"];
if (self.pathLayer == nil) {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0,895.0)];
[path addLineToPoint:CGPointMake(768.0, 895.0)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor blueColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 5.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.view.layer addSublayer:pathLayer];
self.pathLayer = pathLayer;
}
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = timeMax;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[self.pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];