如何把GIF
转换成UIImage
下列加载方法由SDWebImage中的sd_animatedGIFWithData:
改写而成。由该方法我们可以用GIF
的数据生成UIImage
.
Objective-C
版本:
#import "UIImage+GIF.h"
#import <ImageIO/ImageIO.h>
@implementation UIImage (GIF)
+ (UIImage *)animatedGIFImagesWithData:(NSData *)data {
if (!data) {
return nil;
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *staticImage;
if (count <= 1) {
staticImage = [[UIImage alloc] initWithData:data];
} else {
CGFloat scale = 1;
scale = [UIScreen mainScreen].scale;
NSMutableArray<UIImage *>* array = [[NSMutableArray alloc] initWithCapacity:count];
for (int i = 0; i < count; i++) {
CGImageRef CGImage = CGImageSourceCreateImageAtIndex(source, i, NULL);
UIImage *frameImage = [UIImage imageWithCGImage:CGImage scale:scale orientation:UIImageOrientationUp];
[array addObject:frameImage];
CGImageRelease(CGImage);
}
staticImage = [UIImage animatedImageWithImages:array duration:0.0f];
}
CFRelease(source);
return staticImage;
}
@end
Swift
版本:
extension UIImage {
class func animatedGIFImages(data: Data) -> UIImage? {
if let source = CGImageSourceCreateWithData(data as CFData, nil) {
let count = CGImageSourceGetCount(source)
var staticImage: UIImage? = nil
if (count <= 1) {
staticImage = UIImage(data: data)
} else {
let scale = UIScreen.main.scale
var array: [UIImage] = []
for i in 1...count {
if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
let frameImage = UIImage(cgImage: cgImage, scale: scale, orientation: .up)
array.append(frameImage)
} else {
continue
}
}
staticImage = UIImage.animatedImage(with: array, duration: 0)
}
return staticImage
} else {
return nil
}
}
}
在ViewController
中设置:
@IBOutlet weak var imageView: UIImageView!
func setGIF() {
let path = Bundle.main.path(forResource: "testGIF", ofType: ".gif")
if let data = FileManager.default.contents(atPath: path!) {
if let image = UIImage.animatedGIFImages(with: data) {
if image.isGIF() { // image.images != nil
imageView.animationDuration = TimeInterval((image.images?.count ?? 0) / 10)
imageView.animationImages = image.images
imageView.startAnimating()
}
}
}
}
网友评论