【发布时间】:2023-03-17 11:58:01
【问题描述】:
当用户点击按钮时,我正在屏幕上画一个圆圈。动画持续时间已设置,并且 from 和 to 值也已设置。
我想要实现的是,动画应该以某种方式开始,因为用户长按按钮并继续直到他保持在屏幕上的点击,即长按的持续时间。 用户一抬起手指,圆圈就应该停止到到目前为止它已经完成的位置。
这是我的代码:
-(void)startCircularAnimation{
int radius = 50;
CAShapeLayer *circle = [CAShapeLayer layer];
// Make a circular shape
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
cornerRadius:radius].CGPath;
// Center the shape in self.view
circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
CGRectGetMidY(self.view.frame)-radius);
// Configure the apperence of the circle
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor redColor].CGColor;
circle.lineWidth = 5;
// Add to parent layer
[self.view.layer addSublayer:circle];
// Configure animation
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration = 15.0;
drawAnimation.repeatCount = 1.0; // Animate only once..
// Animate from no part of the stroke being drawn to the entire stroke being drawn
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:counter/drawAnimation.duration];
// Experiment with timing to get the appearence to look the way you want
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
// Add the animation to the circle
[circle addAnimation:drawAnimation forKey:@"draw"];
}
此方法执行动画,并且从我在长按处理程序方法的触摸开始情况下启动的计时器计算出起始值。我无法获得完美的长按持续时间。
长按事件方法是这样的。
- (void)_handleLongPressGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{
switch (gestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
{
counter = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(incrementCounter) userInfo:nil repeats:YES];
}
case UIGestureRecognizerStateEnded:{
NSLog(@"State ended");
[timer invalidate];
break;
}
case UIGestureRecognizerStateCancelled:{
NSLog(@"State cancelled");
break;
}
case UIGestureRecognizerStateFailed:
{
break;
}
default:
break;
}
}
增量计数器方法如下
- (void)incrementCounter {
counter++;
[self startCircularAnimation];
}
在用户将手指放在屏幕上之前,这并没有给我绘制圆圈所需的效果。
请在代码中提出一些建议以获得所需的功能。
提前致谢。
【问题讨论】:
标签: ios uigesturerecognizer nstimer cabasicanimation cashapelayer