iOS 开发-GIF动图最后停止的方法

2023-03-28  本文已影响0人  左方
效果

需求要求做到播放完一个GIF图之后,永久的停下来。网上找了很多方法,实现效果都不理想。
最后解决的思路就是手动控制GIF播放,用最后一帧的图片替换GIF。

NSString *gifPath = [[NSBundle mainBundle] pathForResource:GIF图名称 ofType:@"gif"];
NSData *gifData = [[NSData alloc] initWithContentsOfFile:gifPath];
//拿到图像数据
CGImageSourceRef gifSource = CGImageSourceCreateWithData(CFBridgingRetain(gifData), nil);
//拿到图像源中的图像数
size_t gifCount =CGImageSourceGetCount(gifSource);
NSMutableArray *frames = [[NSMutableArray alloc]init];
for(size_t i =0; i< gifCount; i++) {
    //根据图像源中指定索引处的数据,创建图像。
    CGImageRef imageRef =CGImageSourceCreateImageAtIndex(gifSource, i,NULL);
    UIImage*image = [UIImage imageWithCGImage:imageRef];
    [frames addObject:image];
    CGImageRelease(imageRef);//注意释放资源
}
CFRelease(gifSource);//注意释放资源

//拿到最后一帧图像,多复制几个,增加GIF动画停下效果的容错。
UIImage *lastImg = [frames lastObject];
for (int i=0; i<5; i++) {
    [frames addObject:lastImg];
}
//使用以上资源生成GIF图像
UIImage *customImg = [UIImage animatedImageWithImages:frames duration:3];

[self.speechRecognitionBtn setImage:customImg forState:UIControlStateNormal];
[self.speechRecognitionBtn setImage:customImg forState:UIControlStateHighlighted];
//在播放结束后,把GIF替换为最后一帧图像
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self.speechRecognitionBtn setImage:lastImg forState:UIControlStateNormal];
    [self.speechRecognitionBtn setImage:lastImg forState:UIControlStateHighlighted];
});
上一篇 下一篇

猜你喜欢

热点阅读