XZ_iOS之加载gif动画

1、使用 webView 加载本地gif

实现代码:

guard let bundle = Bundle.main.path(forResource: "duck.gif", ofType: nil),
            let gif = NSData.init(contentsOfFile: bundle)
        else {
            return
        }
        
        
        let webView = UIWebView.init(frame: CGRect(x: 50, y: 100, width: 280, height: 200))
        view.addSubview(webView)
        
        let url = URL(fileURLWithPath: bundle)

        webView.load(gif as Data, mimeType: "image/gif", textEncodingName: String(), baseURL: url)

OC代码实现:XZ_iOS之使用WebView实现开机动画效果

2、使用 SDWebImage 加载本地 gif

guard let bundle = Bundle.main.path(forResource: "duck.gif", ofType: nil),
            let gif = NSData.init(contentsOfFile: bundle)
            else {
                return
        }
        
        let imageView = UIImageView.init(frame: CGRect(x: 50, y: 100, width: 280, height: 200))
        
        // 使用 imageData 加载
        imageView.image = UIImage.sd_animatedGIF(with: gif as Data)
        
        view.addSubview(imageView)

3、使用 SDWebImage 加载网络 gif

Swift 4.0之后, 使用 UIImageView + WebCache 类中的 sd_setImageWithURL: placeholderImage: 方法 加载 GIF 图片只能加载第一帧,图片不会动。需要 pod SDWebImage/GIF 框架,并使用 FLAnimatedImageView 作为 imageView 进行加载 gif即可。原因是:4.0版本之后,SDWebImage 使用  FLAnimatedImage 类处理动图。


代码实现:
FLAnimatedImageView *_imageView;

_imageView.frame = CGRectMake(0, 0, size.width, size.height);
 [_imageView sd_setImageWithURL:_url placeholderImage:_placeholder options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL* targetUrl) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _progressView.progress = (float)receivedSize / expectedSize;
            });
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image == nil) {
                return;
            }
            [self setImagePosition:image];
        }];



猜你喜欢

转载自blog.csdn.net/understand_xz/article/details/79239851