iOS播放動態GIF圖片

來源:互聯網
上載者:User

標籤:

 

 《轉》

 

 圖片分為靜態和動態兩種,圖片的格式有很多種,在開發中比較常見的是.png和.jpg的靜態圖片,但有的時候在App中需要播放動態圖片,比如.gif格式的小表情頭像,在IOS中並沒有提供直接顯示動態圖片的控制項,下面就介紹幾種顯示動態圖片的方式。

 

 

  <一>  UIImageView用來顯示圖片, 使用UIImageView中的動畫數組來實現圖片的動畫效果

 
    //建立UIImageView,添加到介面    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];    [self.view addSubview:imageView];    //建立一個數組,數組中按順序添加要播放的圖片(圖片為靜態圖片)    NSMutableArray *imgArray = [NSMutableArray array];    for (int i=1; i<7; i++) {        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"clock%02d.png",i]];        [imgArray addObject:image];    }    //把存有UIImage的數組賦給動畫圖片數組    imageView.animationImages = imgArray;    //設定執行一次完整動畫的時間長度    imageView.animationDuration = 6*0.15;    //動畫重複次數 (0為重複播放)    imageView.animationRepeatCount = 0;    //開始播放動畫    [imageView startAnimating];    //停止播放動畫  - (void)stopAnimating;//判斷是否正在執行動畫  - (BOOL)isAnimating;

  <二>  用UIWebView來顯示動態圖片

    //得到圖片的路徑    NSString *path = [[NSBundle mainBundle] pathForResource:@"happy" ofType:@"gif"];    //將圖片轉為NSData    NSData *gifData = [NSData dataWithContentsOfFile:path];    //建立一個webView,添加到介面    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 150, 200, 200)];    [self.view addSubview:webView];    //自動調整尺寸    webView.scalesPageToFit = YES;    //禁止滾動webView.scrollView.scrollEnabled = NO;    //設定透明效果    webView.backgroundColor = [UIColor clearColor];webView.opaque = 0;    //載入資料    [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

  <三>  用第三方GifView顯示本地圖片

  GifView是封裝好的一個類,可以直接匯入程式中,然後建立對象,來顯示動態圖片;需要注意的是,GifView是MRC的,因此在ARC工程中使用它,需要修改標記 –fno-objc-arc

//方式一:顯示本地Gif圖片    //將圖片轉為NSData資料    NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bird" ofType:@"gif"]];    //建立一個第三方的View顯示圖片    GifView *dataView = [[GifView alloc] initWithFrame:CGRectMake(0, 300, 200, 100) data:localData];    [self.view addSubview:dataView];//方式二:顯示本地Gif圖片    //得到圖片的路徑NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"gif"];//建立一個第三方的View顯示圖片    GifView *dataView2 = [[GifView alloc] initWithFrame:CGRectMake(200, 300, 150, 100) filePath:path];    [self.view addSubview:dataView2];//方式三:顯示從網路擷取的Gif圖片    // 網狀圖片    NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic19.nipic.com/20120222/8072717_124734762000_2.gif"]];    //建立一個第三方的View顯示圖片    GifView *dataViewWeb = [[GifView alloc] initWithFrame:CGRectMake(20, 420, 280, 100) data:urlData];    [self.view addSubview:dataViewWeb];

GifView.h

#import <UIKit/UIKit.h>#import <ImageIO/ImageIO.h>@interface GifView : UIView {    CGImageSourceRef gif;    NSDictionary *gifProperties;    size_t index;    size_t count;    NSTimer *timer;}- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath;- (id)initWithFrame:(CGRect)frame data:(NSData *)_data;@end

GifView.m

#import "GifView.h"#import <QuartzCore/QuartzCore.h>@implementation GifView- (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.12 target:self selector:@selector(play) userInfo:nil repeats:YES];        [timer fire];    }    return self;}- (id)initWithFrame:(CGRect)frame data:(NSData *)_data{        self = [super initWithFrame:frame];    if (self) {                gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]                                                     forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];       gif = CGImageSourceCreateWithData((CFDataRef)_data, (CFDictionaryRef)gifProperties);        count =CGImageSourceGetCount(gif);        timer = [NSTimer scheduledTimerWithTimeInterval:0.12 target:self selector:@selector(play) userInfo:nil repeats:YES];        [timer fire];    }    return self;}-(void)play{    index ++;    index = index%count;    CGImageRef ref = CGImageSourceCreateImageAtIndex(gif, index, (CFDictionaryRef)gifProperties);    self.layer.contents = (id)ref;    CFRelease(ref);}-(void)removeFromSuperview{    NSLog(@"removeFromSuperview");    [timer invalidate];    timer = nil;    [super removeFromSuperview];}- (void)dealloc {    NSLog(@"dealloc");    CFRelease(gif);    [gifProperties release];    [super dealloc];}@end

<四> 總結

  1、通過UIImageView顯示動畫效果,實際上是把動態圖拆成了一組靜態圖,放到數組中,播放的時候依次從數組中取出。如果播放的圖片比較少佔得記憶體比較小或者比較常用(比如工具條上一直顯示的動態小表徵圖),可以選擇用imageNamed:方式擷取圖片,但是通過這種方式加到記憶體中,使用結束,不會自己釋放,多次播放動畫會造成記憶體溢出問題。因此,對於大圖或經常更換的圖,在取圖片的時候可以選擇imageWithContentsOfFile:方式擷取圖片,最佳化記憶體。

  2、使用UIWebView顯示圖片需要注意顯示圖片的尺寸與UIWebView尺寸的設定,如果只是為了顯示動態圖片,可以禁止UIWebView滾動。在顯示動態圖片的時候,即使是動圖的背景處為透明,預設顯示出來是白色背景,這個時候需要手動設定UIWebView的透明才能達到顯示動圖背景透明的效果。

  3、第三方的GifView使用比較簡單,把類匯入即可。但是GifView是MRC的,因此在ARC環境下,需要對類進行標識。

  4、UIImageView與第三方的GifView都是通過定時器來控製圖片類比的動畫,播放的時候是設定每一幀的時間長度,因此在使用的時候,要盡量與動圖原本的時間長度靠近,不然動畫效果會有些奇怪。而通過UIWebView載入Gif動圖的時候會保持原有的幀速,不需要再次設定。

 

iOS播放動態GIF圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.