iOS 播放GIF图

本文记录两种在iOS上播放GIF的方法

第一种:用UIWebView播放GIF图

- (void)playGIFWithWeb{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"gif"];
    NSData *gifData = [NSData dataWithContentsOfFile:path];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    [self.view addSubview:webView];
}

如果想让webView的内容自适应webView的bounds,可以在其delegate的webViewDidFinishLoad方法中调整内容大小

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    CGSize contentSize = webView.scrollView.contentSize;
    CGSize webSize = webView.bounds.size;
    CGFloat scale = webSize.height/contentSize.height;
    if (webSize.width/contentSize.width < webSize.height/contentSize.height) {
        scale = webSize.width/contentSize.width;
    }
    webView.scrollView.minimumZoomScale = scale;
    webView.scrollView.maximumZoomScale = scale;
    webView.scrollView.zoomScale = scale;
}

第二种:把GIF图转换成一组图片,然后在UIImageView上播放帧动画(需要添加ImageIO.framework库,导入#import 头文件)

- (void)playGIFWithImageView{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"gif"];
    NSData *gifData = [NSData dataWithContentsOfFile:path];
    CGImageSourceRef  sourceRef = CGImageSourceCreateWithData((CFDataRef)gifData, NULL);
    
    // 获取图片个数
    size_t count = CGImageSourceGetCount(sourceRef);
    NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:count];
    for (size_t i = 0; i

你可能感兴趣的:(iOS 播放GIF图)