import UIKit
import ImageIO
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// 加载Gif图片, 并且转成Data类型,"my.gif就是gif图片"
guard let path = Bundle.main.path(forResource: "my.gif", ofType: nil) else { return }
guard let data = NSData(contentsOfFile: path)else { return }
// 从data中读取数据: 将data转成CGImageSource对象
guard let imageSource = CGImageSourceCreateWithData(data, nil) else { return }
let imageCount = CGImageSourceGetCount(imageSource)
// 便利所有的图片
var images = [UIImage]()
var totalDuration : TimeInterval =0
for i in 0..
// .取出图片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
let image = UIImage(cgImage: cgImage)
if i == 0 {
imageView.image = image
}
images.append(image)
// 取出持续的时间
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { continue }
guard let gifDict = (properties as NSDictionary)[kCGImagePropertyGIFDictionary] as? NSDictionaryelse { continue }
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumberelse { continue }
totalDuration += frameDuration.doubleValue
}
// 设置imageView的属性
imageView.animationImages = images
imageView.animationDuration = totalDuration
imageView.animationRepeatCount = 0
// 开始播放
imageView.startAnimating()
}
}