Swift - GIF动态图片的播放(分别使用SwiftGif和YLGIFImage-Swift)
默认情况下 UIImage 是不支持动态 gif 图像的,好在网上有很多优秀的第三方扩展库可以实现。本文介绍其中比较好用的两个:SwiftGif 和 YLGIFImage-Swift。
GitHub地址:https://github.com/bahlo/SwiftGif
hangge_1060.zip
二,YLGIFImage-Swift
YLGIFImage-Swift 是YLGIFImage的 Swift 实现 。YLGIFImage异步化GIF图像类和图像查看器支持 播放/停止 GIF图像。
1,配置说明
将下载下来的 YLGIFImage.swift 和 YLImageView.swift 添加到项目中。

2,使用样例

(2)测试代码
一,SwiftGif
SwiftGif 是 Swift 对 UIImage 的扩展,实现了对 Gif 动画图像的支持。GitHub地址:https://github.com/bahlo/SwiftGif
1,配置说明
将下载下来的 SwiftGifCommon 文件夹添加到项目中即可。(或者将里面的 UIImage+Gif.swift 添加进来也可以)

2,使用样例
SwiftGif有两种方式加载gif图像,分别是:
(1)通过文件名初始化:UIImage.gifWithName()
(2)通过NSData初始化:UIImage.gifWithData()
SwiftGif有两种方式加载gif图像,分别是:
(1)通过文件名初始化:UIImage.gifWithName()
(2)通过NSData初始化:UIImage.gifWithData()

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let jeremyGif = UIImage.gifWithName("image1") let imageView = UIImageView(image: jeremyGif) imageView.frame = CGRect(x: 10.0, y: 20.0, width: 290.0, height: 180) view.addSubview(imageView) let imageData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("image2", withExtension: "gif")!) let advTimeGif = UIImage.gifWithData(imageData!) let imageView2 = UIImageView(image: advTimeGif) imageView2.frame = CGRect(x: 10.0, y: 222.0, width: 290.0, height: 202.0) view.addSubview(imageView2) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }源码下载:

YLGIFImage-Swift 是YLGIFImage的 Swift 实现 。YLGIFImage异步化GIF图像类和图像查看器支持 播放/停止 GIF图像。
1,配置说明
将下载下来的 YLGIFImage.swift 和 YLImageView.swift 添加到项目中。

(1)在StoryBoard中,将 imageView 的 Class 设为:YLImageView

import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var button: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "YLGIFImage Swift" YLGIFImage.setPrefetchNum(5) // Do any additional setup after loading the view, typically from a nib. let path = NSBundle.mainBundle().URLForResource("iwatch", withExtension: "gif")? .absoluteString as String! imageView.image = YLGIFImage(contentsOfFile: path) if imageView.isAnimating() { self.button.setTitle("暂停", forState: UIControlState.Normal) } else { self.button.setTitle("播放", forState: UIControlState.Normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func clicked(button:UIButton) { if imageView.isAnimating() { imageView.stopAnimating() } else { imageView.startAnimating() } if imageView.isAnimating() { self.button.setTitle("暂停", forState: UIControlState.Normal) } else { self.button.setTitle("播放", forState: UIControlState.Normal) } } }
