美文网首页
播放gif图

播放gif图

作者: 7dfa9c18c1d1 | 来源:发表于2016-12-19 23:14 被阅读46次

先看下模拟器的效果


13.gif

gif图其实也是一张张的图片组合在一起,1s如果能播放15帧的话,人眼就不会感到明显的卡顿,一般电影院中的电影是一秒30帧,最近李安拍的新电影,比利林恩是一秒120帧

  • 我们使用系统一个框架ImageIO进行GIF图播放,大概思路是,首先把gif图转换成Data数据,然后通过Data数据获取到CGImageSource,然后通过这个CGImageSource获取一帧一帧的画面和总时间,然后用Image的动画组进行播放

// MARK:- 播放gif图
extension ViewController {
    func playGifPic() {
        // 1、找到gif,并且转成data类型数据
        guard let path = Bundle.main.path(forResource: "demo", ofType: "gif") else {
            return
        }
        guard let data = NSData(contentsOfFile: path) else {
            return
        }
        
        // 2、从data中读取数据,将data转成CGImageSource对象
        guard let imageSource = CGImageSourceCreateWithData(data, nil) else {
            return
        }
        let imageCount = CGImageSourceGetCount(imageSource)
        
        
        // 3、遍历所有的图片
        var imgs = [UIImage]()
        var totalDuaration: TimeInterval = 0
        for i in 0..<imageCount {
            // 3-1、从数组中取出图片
            guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {
                return
            }
            let image = UIImage(cgImage: cgImage)
            if i==0 {
                // 保存第一帧的图
                bjImg.image = image
            }
            imgs.append(image)
            
            
            // 3-2、取出时间
            guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else {
                return
            }
            guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else {
                return
            }
            guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else {
                continue
            }
            totalDuaration += Double(frameDuration)
        }
        
        // 4、设置imageView的属性
        bjImg.animationImages = imgs
        bjImg.animationDuration = totalDuaration
        bjImg.animationRepeatCount = 1
        
        // 5、播放
        bjImg.startAnimating()
    }
}

相关文章

网友评论

      本文标题:播放gif图

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