美文网首页Swift
UIImageView 本地 GIF动图

UIImageView 本地 GIF动图

作者: 小奉不在乎 | 来源:发表于2024-03-25 13:06 被阅读0次

网络加载 GIF 动图直接使用 URL加载就行,本地的得给他开个大招才行

extension UIImageView {
    
    func load(local path: String) {
        if path.lastPathComponent.lowercased().hasSuffix(".gif") {
            // 确保URL有效
            let gifUrl = URL.init(fileURLWithPath: path)
            
            // 创建GIF图片源
            if let gifSource = CGImageSourceCreateWithURL(gifUrl as CFURL, nil) {
                // 获取GIF图有多少帧
                let gifCount = CGImageSourceGetCount(gifSource)
                // 创建一个数组来存储每一帧的UIImage
                var voiceImages = [UIImage]()
                  
                for i in 0..<gifCount {
                    // 由数据源gifSource生成一张CGImage类型的图片
                    let imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, nil)
                      
                    // 创建UIImage对象
                    let image = UIImage(cgImage: imageRef!)
                      
                    // 将图片添加到数组中
                    voiceImages.append(image)
                }
                // 设置_iconImageView的初始图片为GIF的第一帧
                self.image = voiceImages.first
                  
                // 设置_iconImageView的动画帧
                self.animationImages = voiceImages
                  
                // 设置动画的持续时间,值越小,运动速度越快
                self.animationDuration = Double(voiceImages.count) * 0.1
                  
                // 设置动画重复次数,0表示无限循环
                self.animationRepeatCount = 0
                  
                // 开始动画播放
                self.startAnimating()
            } else {
                self.image = UIImage(contentsOfFile: path)
            }
        } else {
            self.image = UIImage(contentsOfFile: path)
        }
    }
}

具体使用

exImageView.load(local: path)

相关文章

网友评论

    本文标题:UIImageView 本地 GIF动图

    本文链接:https://www.haomeiwen.com/subject/lfwdtjtx.html