iOS Gif动画播放

这里记录下我实现在iOS端上进行Gif动画播放的代码。


调用代码:

@interface ViewController ()


@property (nonatomic , strong) QGifView *gifView;



@end

@implementation ViewController


- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_gifView startGif];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"snow" withExtension:@"gif"];
    
    _gifView = [[QGifView alloc] initWithCenter:CGPointMake(self.view.bounds.size.width / 2, 13) fileURL:fileUrl];
    
    _gifView.backgroundColor = [UIColor clearColor];
    
    _gifView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    
    
    [self.view addSubview:_gifView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(0, 0, 100, 60);
    btn.center = CGPointMake(100, self.view.bounds.size.height - 50);
    btn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [btn setTitle:@"Start Gif" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(startGif) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn2.frame = CGRectMake(0, 0, 100, 60);
    btn2.center = CGPointMake(220, self.view.bounds.size.height - 50);
    btn2.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [btn2 setTitle:@"Stop Gif" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(stopGif) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
}
- (void)startGif
{
    [_gifView startGif];
}

- (void)stopGif
{
    [_gifView stopGif];
}


GIf播放View 实现

QGifView.h

#import <UIKit/UIKit.h>


@interface QGifView : UIView

- (id) initWithCenter:(CGPoint) center fileURL:(NSURL *)fileURL;
- (void) startGif;
- (void) stopGif;


@end

QGifView.m

#import "QGifView.h"

#import <ImageIO/ImageIO.h>
#import <QuartzCore/QuartzCore.h>

@interface QGifView()
@property (nonatomic , strong) NSMutableArray *frames;

@property (nonatomic , strong) NSMutableArray *frameDelayTimes;

@property (nonatomic , assign) CGFloat totalTime;
@property (nonatomic , assign) CGFloat width;
@property (nonatomic , assign) CGFloat height;


@end



@implementation QGifView
/*
 * @brief resolving gif information
 */

void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes, CGFloat *totalTime,CGFloat *gifWidth, CGFloat *gifHeight)
{
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);
    
    // get frame count
    size_t frameCount = CGImageSourceGetCount(gifSource);
    for (size_t i = 0; i < frameCount; ++i) {
        // get each frame
        CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        [frames addObject:(__bridge id)frame];
        CGImageRelease(frame);
        
        // get gif info with each frame
        NSDictionary *dict = (NSDictionary*)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL));
        NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
        
        // get gif size
        if (gifWidth != NULL && gifHeight != NULL) {
            *gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
            *gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
        }
        
        // kCGImagePropertyGIFDictionary中kCGImagePropertyGIFDelayTime,kCGImagePropertyGIFUnclampedDelayTime值是一样的
        NSDictionary *gifDict = [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary];
        [delayTimes addObject:[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime]];
        
        if (totalTime) {
            *totalTime = *totalTime + [[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime] floatValue];
        }
    }
}



- (id) initWithCenter:(CGPoint) center fileURL:(NSURL *)fileURL
{
    if (self = [super initWithFrame:CGRectZero])
    {
        _frames = [NSMutableArray array];
        _frameDelayTimes = [NSMutableArray array];
        
        _width = 0;
        _height = 0;
        
        if (fileURL) {
            getFrameInfo((__bridge CFURLRef)fileURL, _frames, _frameDelayTimes, &_totalTime, &_width, &_height);
        }
        
        self.frame = CGRectMake(0, 0, _width, _height);
        self.center = center;
        
    }
    return self;
}

- (void) startGif
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
    CGFloat currentTime = 0;
    int count = _frameDelayTimes.count;
    for (int i = 0; i < count; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];
        currentTime += [[_frameDelayTimes objectAtIndex:i] floatValue];
    }
    [animation setKeyTimes:times];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for (int i = 0; i < count; ++i) {
        [images addObject:[_frames objectAtIndex:i]];
    }
    
    [animation setValues:images];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = _totalTime;
    animation.delegate = self;
    animation.repeatCount = 50;
    
    [self.layer addAnimation:animation forKey:@"gifAnimation"];
    
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.layer.contents = nil;
}


- (void) stopGif
{
    [self.layer removeAllAnimations];
}

@end

代码下载:http://download.csdn.net/detail/qqmcy/8502055


发布了490 篇原创文章 · 获赞 22 · 访问量 115万+

猜你喜欢

转载自blog.csdn.net/qqMCY/article/details/44263437