IOS gif animation playback

Source: Internet
Author: User

Here is the code that I implemented to animate GIF animations on iOS.


Calling code:

@interface Viewcontroller () @property (nonatomic, strong) Qgifview *gifview; @end @implementation viewcontroller-(void)    Viewdidappear: (BOOL) animated{[Super viewdidappear:animated]; [_gifview startgif];}    -(void) viewdidload {[Super viewdidload];        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,) 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 (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 (, 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 playback View Implementation

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, NSMut Ablearray *frames, Nsmutablearray *delaytimes, CGFloat *totaltime,cgfloat *gifwidth, CGFloat *gifHeight) {CGImageSource        Ref 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 = Cgimagesourcecreateimageat        Index (Gifsource, I, NULL);        [Frames AddObject: (__bridge ID) frame];                Cgimagerelease (frame); Get GIF info with EAch frame nsdictionary *dict = (nsdictionary*) cfbridgingrelease (Cgimagesourcecopypropertiesatindex (GifSource, I, NU        LL));                NSLog (@ "Kcgimagepropertygifdictionary%@", [Dict Valueforkey: (nsstring*) kcgimagepropertygifdictionary]); Get GIF size if (gifwidth! = NULL && gifheight! = null) {*gifwidth = [[Dict valueforkey: (NSS            tring*) kcgimagepropertypixelwidth] floatvalue];        *gifheight = [[Dict valueforkey: (nsstring*) kcgimagepropertypixelheight] floatvalue];        }//Kcgimagepropertygifdictionary The Kcgimagepropertygifdelaytime,kcgimagepropertygifunclampeddelaytime value is the same        Nsdictionary *gifdict = [dict valueforkey: (nsstring*) kcgimagepropertygifdictionary];                [Delaytimes addobject:[gifdict Valueforkey: (nsstring*) kcgimagepropertygifdelaytime]]; if (totaltime) {*totaltime = *totaltime + [[gifdict Valueforkey: (nsstring*) kcgimagepropertygifdelaytime] Float        Value]; }}}-(ID) Initwithcenter: (cgpoint) Center FileURL: (Nsurl *) fileurl{if (self = [Super Initwithframe:cgrectzero]) {_FR        Ames = [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

Code Download: http://download.csdn.net/detail/qqmcy/8502055


IOS gif animation playback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.