美文网首页iOS Developer
iOS - Gif图片本地播放

iOS - Gif图片本地播放

作者: 黄晓坚 | 来源:发表于2017-08-10 23:10 被阅读130次

在本地Gif播放中 我们需要使用到import ImageIO,大多数图片的处理中都可能需要用到import ImageIO

关于Gif播放了解更多

第一步:加载资源 并转化成Data

 // 1. 加载图片 并且转换成data类型
        guard let path = Bundle.main.path(forResource: "demo.gif", ofType: nil) else {
        
            return
        }
       
        guard let data = NSData(contentsOfFile: path) else {
            
            return
        }

第二步:从data中读取数据: 将data转成CGImageSource对象

  // 2. 从data中读取数据: 将data转成CGImageSource对象
        
        guard let imageSource = CGImageSourceCreateWithData(data, nil) else { return }
        
        let imageCount = CGImageSourceGetCount(imageSource)

第三步: 遍历所拿到的imageCount,并且取出Gif图片的每一帧的时间,将每一帧的时间累加则得到Gif播放的总时间,若觉得Gif播放速度太快则可以totaleDuration += (frameDuration.doubleValue + 0.1)在每一帧的时间上稍微加点时间来使得本地Gif播放速度慢一点,若太慢则显得卡顿。

        var images = [UIImage]()
        var totaleDuration : TimeInterval = 0
        
        for i in 0..<imageCount {
            
            // 3.1 取出图片
            guard let cgimage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue
            }
            
            let image = UIImage(cgImage:cgimage)
            
//            if i == 0 {
//                imageView.image = image
//            }
            
            images.append(image)
            
            // 3.2 取出持续时间
            guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else { continue }
            
            guard let GifDic = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else { continue }
            // 3.2.1 取出每一帧图片时间
            guard let frameDuration = GifDic[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
         
            // 3.2.2 计算Gif播放的总时间
            totaleDuration += frameDuration.doubleValue
        }

第四步:设置imageView的属性:例如基本熟悉animationImages动画、播放时间animationDuration、重复播放次数animationRepeatCount 次数为1则播放一次,若为0则一直播放,isUserInteractionEnabled: Bool是否交互

// 4 设置imageView的属性
        imageView.animationImages = images
        imageView.animationDuration = totaleDuration
        imageView.animationRepeatCount = 1

第五步:开始动画效果
// 5 开始动画 imageView.startAnimating()

Demo下载

相关文章

网友评论

    本文标题:iOS - Gif图片本地播放

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