背景:
项目中有很多视频展示,点击播放的功能,视频的展示封面需要获取视频第一帧画面显示。又因为在列表中用的多,滑动时每次去获取比较耗时。
思路:
创建UIImageView的分类,参考SDWebImage实现,获取到视频第一帧画面时,以视频链接哈希串作为key,image作为值,利用SDImageCache进行图片的三级缓存(磁盘、内存和网络层)。
流程:
- 给UIImageView设置图片;
- 先去缓存查找,有则返回;
- 再去磁盘查找,有则返回;
- 都没找到,截取视频某一帧画面转为image,缓存至磁盘。
实现:
#import "UIButton+VideoImage.h"
#import <SDWebImage/SDImageCache.h>
@implementation UIButton (VideoImage)
- (void)videoImageWithvideoURL:(NSURL *)videoURL atTime:(NSTimeInterval)time {
//先从缓存中查找是否有图片
SDImageCache *cache = [SDImageCache sharedImageCache];
UIImage *memoryImage = [cache imageFromMemoryCacheForKey:videoURL.absoluteString];
if (memoryImage) {
[self setBackgroundImage:memoryImage forState:UIControlStateNormal];
return;
}else{
//再从磁盘中查找是否有图片
UIImage *diskImage = [cache imageFromDiskCacheForKey:videoURL.absoluteString];
if (diskImage) {
[self setBackgroundImage:diskImage forState:UIControlStateNormal];
return;
}
}
if (!time) {
time = 1;
}
//如果都不存在,开启异步线程截取对应时间点的画面,转成图片缓存至磁盘
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError *thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
if(!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
dispatch_async(dispatch_get_main_queue(), ^{
SDImageCache * cache = [SDImageCache sharedImageCache];
[cache storeImage:thumbnailImage forKey:videoURL.absoluteString toDisk:YES completion:nil];
[self setBackgroundImage:thumbnailImage forState:UIControlStateNormal];
});
});
}
@end
网友评论