How to display GIF images in iOS development
We know that a Gif is composed of a burst of pictures, and the playing of each frame may often be different. Observe the above two examples, they do not often process the display of each frame in the Gif. The result is that each frame in the Gif is played forward at a fixed speed, obviously, this does not always meet the requirements.
Therefore, I wrote a Gif Parsing tool class to solve the problem of playing each frame and following the display time corresponding to each frame.
The procedure is as follows:
1. First, use CGImageSource in the ImageIO library in the Gif file.
2. Get the total number of frames in the Gif file and the display time of each frame through CGImageSource.
3. Use CAKeyframeAnimation to play the GIF animation.
The following is the code for parsing and playing Gif tools:
//// SvGifView. h // SvGifSample /// Created by maple on 3/28/13. // Copyright (c) 2013 smileEvday. all rights reserved. // # import @ interface SvGifView: UIView/** @ brief desingated initializer */-(id) initWithCenter :( CGPoint) center fileURL :( NSURL *) fileURL; /** @ brief start Gif Animation */-(void) startGif;/** @ brief stop Gif Animation */-(void) stopGif; /** @ brief get frames image (CGImageRef) in Gif */+ (NSA Rray *) framesInGif :( NSURL *) fileURL; @ end // SvGifView. m // SvGifSample /// Created by maple on 3/28/13. // Copyright (c) 2013 smileEvday. all rights reserved. // # import "SvGifView. h "# import/** @ 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 countsize_t frameCount = CGImageSourceGetCount (gifSource); for (size_t I = 0; I <frameCount; ++ I) {// get each frameCGImageRef frame = CGImageSourceCreateImageAtIndex (gifSource, I, NULL); [frames addObject :( id) frame]; CGImageRelease (frame ); // get gif info with each frameNSDictionary * dict = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex (gifSourc E, I, NULL); NSLog (@ "kCGImagePropertyGIFDictionary % @", [dict valueForKey :( NSString *) kCGImagePropertyGIFDictionary]); // get gif sizeif (gifWidth! = NULL & gifHeight! = NULL) {* gifWidth = [[dict valueForKey :( NSString *) kCGImagePropertyPixelWidth] floatValue]; * gifHeight = [[dict valueForKey :( NSString *) kCGImagePropertyPixelHeight] floatValue];} // The region in the region. The region value is the same as NSDictionary * gifDict = [dict valueForKey :( NSString *) region]; [delayTimes addObject: [gifDict valueForKey :( NSString *) region]; if (totalTime) {* totalTime = * totalTime + [[gifDict valueForKey :( NSString *) values] floatValue] ;}}@ interface SvGifView () {NSMutableArray * _ frames; optional * _ frameDelayTimes; CGFloat _ totalTime; // secondsCGFloat _ width; CGFloat _ height;} @ end @ implementation SvGifView-(id) initWithCenter :( CGPoint) center fileURL :( NSURL *) fileURL; {self = [super initWithFrame: CGRectZero]; if (self) {_ frames = [[NSMutableArray alloc] init]; _ frameDelayTimes = [[nsmutablearablearray alloc] init]; _ width = 0; _ height = 0; if (fileURL) {getFrameInfo (CFURLRef) fileURL, _ frames, _ frameDelayTimes, & _ totalTime, & _ width, & _ height);} self. frame = CGRectMake (0, 0, _ width, _ height); self. center = center;} return self;} + (NSArray *) framesInGif :( NSURL *) fileURL {parameters * frames = [NSMutableArray failed: 3]; NSMutableArray * delays = [NSMutableArray failed: 3]; getFrameInfo (CFURLRef) fileURL, frames, delays, NULL, NULL); return frames;}-(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 Syntax: 3]; for (int I = 0; I <count; ++ I) {[images addObject: [_ frames objectAtIndex: I];} [animation setValues: images]; [animation setTimingFunction: [edicamatimingfunction functionWithName: kCAMediaTimingFunctionLinear]; animation. duration = _ totalTime; animation. delegate = self; animation. repeatCount = 5; [self. layer addAnimation: animation forKey: @ "gifAnimation"];}-(void) stopGif {[self. layer removeAllAnimations];} // remove contents when animation end-(void) animationDidStop :( CAAnimation *) anim finished :( BOOL) flag {self. layer. contents = nil;} // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. -(void) drawRect :( CGRect) rect {// Drawing code}
@ End
The code is very short and easy to explain. The C function at the beginning is mainly used to parse Gif. The C function is used because I want to return multiple messages, while Objective-c can only return one parameter, moreover, Objective-c and c can be easily mixed for programming.
In addition, we will introduce two methods to use UIImageView:
1. Use UIWebView for playback
// Set the position and size CGRect frame = CGRectMake (50, 50,); frame. size = [UIImage imageNamed: @ "guzhang.gif"]. size; // NSData * gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @ "guzhang" ofType: @ "gif"]; // view generation UIWebView * webView = [[UIWebView alloc] initWithFrame: frame]; webView. userInteractionEnabled = NO; // the user cannot interact. [webView loadData: gif MIMEType: @ "image/gif" textEncodingName: nil baseURL: nil]; [self. view addSubview: webView]; [webView release];
2. Break down GIF images into multiple png images and use UIImageView for playback.
The Code is as follows:
UIImageView * gifImageView = [[UIImageView alloc] initWithFrame: [UIScreen mainScreen] bounds]; NSArray * gifArray = [NSArray preview: [UIImage imageNamed: @ "1"], [UIImage imageNamed: @ "2"], [UIImage imageNamed: @ "3"], [UIImage imageNamed: @ "4"], [UIImage imageNamed: @ "5"], [UIImage imageNamed: @ "6"], [UIImage imageNamed: @ "7"], [UIImage imageNamed: @ "8"], [UIImage imageNamed: @ "9"], [UIImage imageNamed: @ "10"], [UIImage imageNamed: @ "11"], [UIImage imageNamed: @ "12"], [UIImage imageNamed: @ "13"], [UIImage imageNamed: @ "14"], [UIImage imageNamed: @ "15"], [UIImage imageNamed: @ "16"], [UIImage imageNamed: @ "17"], [UIImage imageNamed: @ "18"], [UIImage imageNamed: @ "19"], [UIImage imageNamed: @ "20"], [UIImage imageNamed: @ "21"], [UIImage imageNamed: @ "22"], nil]; gifImageView. animationImages = gifArray; // Animated Image array gifImageView. animationDuration = 5; // Duration Required for executing a complete animation. animationRepeatCount = 1; // Number of animation repetitions [gifImageView startAnimating]; [self. view addSubview: gifImageView]; [gifImageView release];
Note: This method cannot be used if the interval of each GIF animation is different.