UIImageView显示GIF图片

UIImageView+Kit.h文件

#import

NS_ASSUME_NONNULL_BEGIN

@interface UIImageView (Kit)

- (void)loadGIFImageNamed:(NSString *)name;

@end

NS_ASSUME_NONNULL_END


#import "UIImageView+Kit.h"

@implementation UIImageView (Kit)

- (void)loadGIFImageNamed:(NSString *)name {

    /// 找到GIF图片文件路径

    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:name withExtension:@"gif"];


    /// 将GIF图片转换成对应的图片资源

    CGImageSourceRefimageSourceRef =CGImageSourceCreateWithURL((__bridgeCFURLRef)fileUrl,NULL);


    /// 从图片资源中获取图片帧数,即由多少图片元素组成(注:GIF图片本质是有多张图片合成流动图片)

    size_timageCount =CGImageSourceGetCount(imageSourceRef);


    /// 定义数组拆分图片源

    NSMutableArray*images = [NSMutableArrayarrayWithCapacity:imageCount];


    /// 定义动画持续时长

    floatanimationDuration =0.f;

    /// 循环获取图片元素

    for(size_ti =0; i < imageCount; i++) {

        /// 从图片资源中取出图片元素,即每一帧的图片

        CGImageRefimageRef =CGImageSourceCreateImageAtIndex(imageSourceRef, i ,NULL);

        ///图片转换

        UIImage*image = [UIImageimageWithCGImage:imageRef];

        ///存储图片

        [imagesaddObject:image];

        ///获取元素图片的信息

        NSDictionary*imageElementInfo = (__bridgeNSDictionary*)CGImageSourceCopyProperties(imageSourceRef,NULL);

        ///获取元素动画信息

        NSDictionary*imageElementGIFInfo = [imageElementInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFDictionary];


        /// 初始化每帧之间间隔的属性。

        CGFloatduration =0.1f;


        NSNumber*unclampedDelayTime = [imageElementGIFInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFUnclampedDelayTime];

        if(unclampedDelayTime) {

            duration= unclampedDelayTime.floatValue;

        }else{

            NSNumber*delayTime = [imageElementGIFInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFDelayTime];

            if(delayTime) {

                duration= delayTime.floatValue;

            }

        }


        /// 获取延迟时间可能为0.f

        if(duration <=0.011f) duration =0.100f;


        animationDuration += duration;


        ///释放内存

        CGImageRelease(imageRef);

    }

    /// 图片控件载入动画图片数组

    self.animationImages= images;

    /// 设置动画持续时长

    self.animationDuration= animationDuration;

    /// 设置动画重复次数

    self.animationRepeatCount = MAXFLOAT;

    ///开启动画

    [self startAnimating];

}

@end

你可能感兴趣的:(UIImageView显示GIF图片)