用UImage承载Gif图片

作者: devchena | 来源:发表于2015-11-09 15:09 被阅读3380次

    1.首先,添加UIImage的扩展到工程中:
    .h

    #import <UIKit/UIKit.h>
    
    @interface UIImage (GIF)
    
    + (UIImage *)sd_animatedGIFNamed:(NSString *)name;
    
    + (UIImage *)sd_animatedGIFWithData:(NSData *)data;
    
    - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
    
    @end
    
    

    .m

    #import "UIImage+GIF.h"
    #import <ImageIO/ImageIO.h>
    
    @implementation UIImage (GIF)
    
    + (UIImage *)sd_animatedGIFWithData:(NSData *)data {
        if (!data) {
            return nil;
        }
    
        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    
        size_t count = CGImageSourceGetCount(source);
    
        UIImage *animatedImage;
    
        if (count <= 1) {
            animatedImage = [[UIImage alloc] initWithData:data];
        }
        else {
            NSMutableArray *images = [NSMutableArray array];
    
            NSTimeInterval duration = 0.0f;
    
            for (size_t i = 0; i < count; i++) {
                CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
    
                duration += [self sd_frameDurationAtIndex:i source:source];
    
                [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
    
                CGImageRelease(image);
            }
    
            if (!duration) {
                duration = (1.0f / 10.0f) * count;
            }
    
            animatedImage = [UIImage animatedImageWithImages:images duration:duration];
        }
    
        CFRelease(source);
    
        return animatedImage;
    }
    
    + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
        float frameDuration = 0.1f;
        CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
        NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
        NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    
        NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
        if (delayTimeUnclampedProp) {
            frameDuration = [delayTimeUnclampedProp floatValue];
        }
        else {
    
            NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
            if (delayTimeProp) {
                frameDuration = [delayTimeProp floatValue];
            }
        }
    
        // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
        // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
        // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
        // for more information.
    
        if (frameDuration < 0.011f) {
            frameDuration = 0.100f;
        }
    
        CFRelease(cfFrameProperties);
        return frameDuration;
    }
    
    + (UIImage *)sd_animatedGIFNamed:(NSString *)name {
        CGFloat scale = [UIScreen mainScreen].scale;
    
        if (scale > 1.0f) {
            NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
    
            NSData *data = [NSData dataWithContentsOfFile:retinaPath];
    
            if (data) {
                return [UIImage sd_animatedGIFWithData:data];
            }
    
            NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
    
            data = [NSData dataWithContentsOfFile:path];
    
            if (data) {
                return [UIImage sd_animatedGIFWithData:data];
            }
    
            return [UIImage imageNamed:name];
        }
        else {
            NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
    
            NSData *data = [NSData dataWithContentsOfFile:path];
    
            if (data) {
                return [UIImage sd_animatedGIFWithData:data];
            }
    
            return [UIImage imageNamed:name];
        }
    }
    
    - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size {
        if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
            return self;
        }
    
        CGSize scaledSize = size;
        CGPoint thumbnailPoint = CGPointZero;
    
        CGFloat widthFactor = size.width / self.size.width;
        CGFloat heightFactor = size.height / self.size.height;
        CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
        scaledSize.width = self.size.width * scaleFactor;
        scaledSize.height = self.size.height * scaleFactor;
    
        if (widthFactor > heightFactor) {
            thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
        }
        else if (widthFactor < heightFactor) {
            thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
        }
    
        NSMutableArray *scaledImages = [NSMutableArray array];
    
        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    
        for (UIImage *image in self.images) {
            [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
            [scaledImages addObject:newImage];
        }
    
        UIGraphicsEndImageContext();
    
        return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
    }
    
    @end
    
    

    2.引入 "UIImage+GIF.h"扩展,调用上面相应的初始化方法,用UIImageView去加载展示即可。

    3.示例,用于App启动动画(亦可制作其他动画效果):

    LaunchAnimationViewController.m

    #import "LaunchAnimationViewController.h"
    #import <UIImage+GIF.h>
    #import "MainViewoController.h"
    
    @interface LaunchAnimationViewController ()
    
    @end
    
    @implementation LaunchAnimationViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
        
        UIImageView *launchAnimationView = [[UIImageView alloc] init];
        // frame可根据图片大小设定
        launchAnimationView.frame = self.view.bounds;
        // 创建gifImage,传入Gif图片名即可
        UIImage *gifImage = [UIImage sd_animatedGIFNamed:@"gifName"];
        launchAnimationView.image = gifImage;
        [self.view addSubview:launchAnimationView];
        
        // 执行隐藏动画,在动画完成后切换主界面
        [UIView animateWithDuration:0.3 delay:1.6 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            launchAnimationView.alpha = 0;
        } completion:^(BOOL finished) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = [[MainViewoController alloc] init];
        }];
    }
    
    @end
    
    

    相关文章

      网友评论

      • 9b27b67eccb4:你这个方法,会无限循环gif次数,有什么办法设置只执行一次?
      • 孤独而无用的灵魂:楼主一生平安!太赞了 :stuck_out_tongue_closed_eyes:
      • c05bd76eafae:你好,這個方法很實用!
        請問可以轉貼你的這篇文章嗎?
        會附上網址與連結,純粹分享用途:D
      • ShayneFcf:UIImageView应该是支持GIF图片的吧!但是这个写的还不错
      • ZyonPaul:学习了
        devchena:@缄默中丶守望 有用就好
      • 改变自己_now:大神学习了

      本文标题:用UImage承载Gif图片

      本文链接:https://www.haomeiwen.com/subject/ycfhhttx.html