市面上播放GIF的控件很多,比较了几款后最后决定使用YYAnimatedImageView
,简单易懂,且不会像FLAnimatedImageView导致内存暴涨
直接上代码
YYAnimatedImageView *gifImageView = [[YYAnimatedImageView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight + 40,scaleFactorForWidth(400), scaleFactorForWidth(302))];
YYImage *img = [YYImage imageNamed:@"snore_gif.gif"];
gifImageView.image = img;
[self addSubview:gifImageView];
此时有个需求,GIF只需播放一遍
//1.获取GIF图的图片总数
NSArray *imagesArray = [self getImageFromGifResource:@"snore_gif"];
//2.监听gif
[RACObserve(gifImageView, currentAnimatedImageIndex) subscribeNext:^(id _Nullable x) {
if ([x integerValue] == imagesArray.count - 1) {
[gifImageView stopAnimating];
}
}];
//这样就会只播放一遍,紫萼停留在最后一帧
获取GIF图片总数
- (NSArray <UIImage *>*)getImageFromGifResource:(NSString *)resource {
NSMutableArray *imageArray = [NSMutableArray array];
// 获取gif url
NSURL *url = [[NSBundle mainBundle] URLForResource:resource withExtension:@"gif"];
// 转换为图片源
CGImageSourceRef gifImageSourceRef = CGImageSourceCreateWithURL((CFURLRef)url, nil);
// 获取图片个数
size_t framesCount = CGImageSourceGetCount(gifImageSourceRef);
for (size_t index = 0; index < framesCount; index ++) {
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifImageSourceRef, index , nil);
UIImage *image = [UIImage imageWithCGImage:imageRef];
[imageArray addObject:image];
CFRelease(imageRef);
}
return imageArray;
}