iPhone 播放Gif动画

来源:互联网 发布:软件测试实例视频 编辑:程序博客网 时间:2024/05/31 06:23

1'导入ImageIO.framework、QuartzCore.framework和MobileCoreServices.framework框架

2‘建立GifAnimationView.h文件

代码:

#import <UIKit/UIkit.h>

#import <ImageIO/ImageIO.h>

#import <MobileCoreServices/MobileCoreServices.h>

 

@interface GifAnimationView:UIView {

    CGImageSourceRef gif;

    Dictionary *gifProperties;

    size_t index;

    size_t count;

    NSTimer *timer;

    int tag_Index;

}

 

@property (nonatomic,assign) int tag_Index;

 

-(id) initWithFrame:(CGRect)frame filePath:(NSString *)filePath;

@end;

3'建立GifAnimationView.m文件

#import "GifAnimationView.h"

 

@implementation GIfAnimationView

@synthesize tag_Index;

 

-(id) initWithFrame:(CGRect)frame filePath:(NSString *)_filePath{

    self = [super initWithFrame:frame];

    if(self){

        gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount] forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];

        gif = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:_filePath],(CFDictionaryRef)gifProperties);

        count = CGImageSourceGetCount(gif);

        timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:(play) userInfo:nil repeats:YES];

        [time fire];

    }

    return self;

}

-(void) play {

    index++;

    index = index%count;

    CGImageRef ref = CGImageSourceCreateImageAtIndex:(gif,index,(CFDictionaryRef)gifProperties);

    self.layer.contents = (id) ref;

}

-(void) removeFromSuperview{

    [timer invalidate];

    timer = nil;

    [super removeFromSuperview];

}

-(void) dealloc{

    CFRelease(gif);

    [gifProperties release];

    [super dealloc];

}

 

4’在AppDelegate.m中调用

NSString *gifFilePath = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];

GifAnimationView *gifView = [[GifAnimationView alloc] initWithFrame:CGRectMake(220,140,40,40)filePath:gifFilePath];

[self.window addSubview:gifView];