- 不废话直接上代码,注意一点要
import ImageIO
//
// GIFImageView.swift
// SugarTools
//
// Created by yuzhengkai on 2020/12/8.
// Copyright © 2020 yzk. All rights reserved.
//
import UIKit
import ImageIO
class GIFImageView: UIImageView {
var gifname: String?
func startGIF() {
guard let path = Bundle.main.path(forResource: gifname, ofType: nil) else {
return
}
let fileurl = URL(fileURLWithPath: path)
guard let data = try? Data(contentsOf: fileurl) else {
return
}
guard let gifsource = CGImageSourceCreateWithData(data as CFData, nil) else {
return
}
//拿到分解多少张图片,也就是有多少帧
let gifcount = CGImageSourceGetCount(gifsource)
var images = [UIImage]()
var totalDuration: TimeInterval = 0
for i in 0..<gifcount {
guard let cgimage = CGImageSourceCreateImageAtIndex(gifsource, i, nil) else {
return
}
let image = UIImage(cgImage: cgimage)
// 如果只有一帧,直接显示
if i == 0 {
self.image = image
}
images.append(image)
//读取时每一帧的属性
guard let properties = CGImageSourceCopyPropertiesAtIndex(gifsource, i, nil) as? [CFString : Any] else {
continue
}
//读取GIF图片信息
guard let gifdict = properties[kCGImagePropertyGIFDictionary] as? [CFString : Any] else {
continue
}
//GIF每一帧的时间
guard let gifduration = gifdict[kCGImagePropertyGIFDelayTime] as? NSNumber else {
continue
}
totalDuration += gifduration.doubleValue
}
self.animationImages = images
self.animationDuration = totalDuration
self.animationRepeatCount = 0
self.startAnimating()
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
网友评论