我知道您的原始实现使用animationImages
,但我不知道animationImages
直接使用连续可变持续时间的方法。但是,这是一个非常简单的功能,可以自己实现。如果这样做,则可以在数组中的图像之间编写动态持续时间值。
在下面的代码中,我替换为自定义步进函数,并在请求停止后animationImages
动态调整持续时间。请注意,这与指定硬结束时间的原始代码略有不同。此代码指定齿轮旋转何时开始减速。
如果你真的有一个硬动画周期,你可以调整调用来stopTheAnimation
考虑你选择的减速因子(我只是在减速期间将持续时间每步增加 10%,直到步数低于给定的阈值):
// my animation stops when the step duration reaches this value:
#define STOP_THRESHOLD_SECONDS 0.1f
#define NUM_IMAGES 35
@implementation ViewController
{
NSMutableArray *imagesArr;
int currentImage;
BOOL stopRequested;
NSTimeInterval duration;
}
-(void) setupTheAnimation {
stopRequested = NO;
currentImage = 0;
duration = 0.9f / NUM_IMAGES;
[self stepThroughImages];
[self performSelector:@selector(stopTheAnimation) withObject:nil afterDelay:4.0];
}
- (void) stepThroughImages {
self.imgView.image = [imagesArr objectAtIndex: currentImage];
if (currentImage == NUM_IMAGES - 1) {
currentImage = 0;
} else {
currentImage++;
}
if (stopRequested && duration < STOP_THRESHOLD_SECONDS) {
// we're slowing down gradually
duration *= 1.1f;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self stepThroughImages];
});
} else if (!stopRequested) {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self stepThroughImages];
});
}
}
-(void) stopTheAnimation {
stopRequested = YES;
}