iOS中GIF图片的分解、合成与显示

题记


如我们iOS开发者所知,目前iOS还没有支持原生展现GIF图片,因此合成和分解GIF图片对于我们处理各种动画效果有着很高的使用价值。话不多说先看看效果图:

  • 这里提供了3个按钮,本质上是两个方法,分解与合成GIF,因为只要有这两个方法的存在,无论我们拿到的是GIF图还是帧图,我们都能简单地在我们的设备上播放GIF。


代码


  • 分解GIF
/// 把gif动图分解成每一帧图片
    ///
    /// - Parameters:
    ///   - imageType: 分解后的图片格式
    ///   - path: gif路径
    ///   - locatioin: 分解后图片保存路径(如果为空则保存在默认路径)
    ///   - imageName: 分解后图片名称
func decompositionImage( _ imageType: imageType, _ path: String, _ locatioin: String = "", _ imageName: String = "") {
        
        //把图片转成data
        let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
        guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
        //计算图片张数
        let count = CGImageSourceGetCount(gifSource)
        
        var dosc: [String] = []
        var directory = ""
        
        //判断是否传入路径,如果没有则使用默认路径
        if locatioin.isEmpty {
            dosc = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            directory = dosc[0] + "/"
        }else{
            let index = locatioin.index(locatioin.endIndex, offsetBy: -1)
            if locatioin.substring(from: index) != "/" {
                directory = locatioin + "/"
            }else{
                directory = locatioin
            }
        }
        
        var imagePath = ""
        //逐一取出
        for i in 0...count-1 {
            guard let imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, nil) else { return }
            let image = UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up)
            
            //根据选择不同格式生成对应图片已经路径
            switch imageType {
            case .jpg:
                guard let imageData = UIImageJPEGRepresentation(image, 1) else { return }
                if imageName.isEmpty {
                    imagePath = directory + "\(i)" + ".jpg"
                }else {
                    imagePath = directory + "\(imageName)" + "\(i)" + ".jpg"
                }
                try? imageData.write(to: URL.init(fileURLWithPath: imagePath), options: .atomic)
            case .png:
                guard let imageData = UIImagePNGRepresentation(image) else { return }
                if imageName.isEmpty {
                    imagePath = directory + "\(i)" + ".png"
                }else {
                    imagePath = directory + "\(imageName)" + "\(i)" + ".png"
                }
                
                //生成图片
                try? imageData.write(to: URL.init(fileURLWithPath: imagePath), options: .atomic)
            }
            
            print(imagePath)
        }
    }


  • 合成GIF
/// 根据传入图片数组创建gif动图
    ///
    /// - Parameters:
    ///   - images: 源图片数组
    ///   - imageName: 生成gif图片名称
    ///   - imageCuont: 图片总数量
func compositionImage(_ images: NSMutableArray, _ imageName: String, _ imageCuont: Int) {
        
        //在Document目录下创建gif文件
        let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let gifPath = docs[0] + "/\(imageName)" + ".gif"
        guard let url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, gifPath as CFString, .cfurlposixPathStyle, false), let destinaiton = CGImageDestinationCreateWithURL(url, kUTTypeGIF, imageCuont, nil) else { return }
        
        //设置每帧图片播放时间
        let cgimageDic = [kCGImagePropertyGIFDelayTime as String: 0.1]
        let gifDestinaitonDic = [kCGImagePropertyGIFDictionary as String: cgimageDic]
        
        //添加gif图像的每一帧元素
        for cgimage in images {
            CGImageDestinationAddImage(destinaiton, (cgimage as AnyObject).cgImage!!, gifDestinaitonDic as CFDictionary)
        }
        
        // 设置gif的彩色空间格式、颜色深度、执行次数
        let gifPropertyDic = NSMutableDictionary()
        gifPropertyDic.setValue(kCGImagePropertyColorModelRGB, forKey: kCGImagePropertyColorModel as String)
        gifPropertyDic.setValue(16, forKey: kCGImagePropertyDepth as String)
        gifPropertyDic.setValue(1, forKey: kCGImagePropertyGIFLoopCount as String)
        
        //设置gif属性
        let gifDicDest = [kCGImagePropertyGIFDictionary as String: gifPropertyDic]
        CGImageDestinationSetProperties(destinaiton, gifDicDest as CFDictionary)
        
        //生成gif
        CGImageDestinationFinalize(destinaiton)
        
        print(gifPath)
    }


  • 播放
  • 这里继承UIImageView定义了一个JJGIFImageView类,增加了一个直接显示GIF图片的方法,只需要把GIF的路径传入,设置GIF时间以及重复次数即可
class JJGIFImageView: UIImageView {
    
    var images: [UIImage] = []
    
    /// GIF图片展示
    ///
    /// - Parameters:
    ///   - path: GIF所在路径
    ///   - duration: 持续时间
    ///   - repeatCount: 重复次数
    public func presentationGIFImage(path: String, duration: TimeInterval, repeatCount: Int) {
        decompositionImage(path)
        displayGIF(duration, repeatCount)
    }
    
    private func decompositionImage(_ path: String) {
        //把图片转成data
        let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
        guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
        //计算图片张数
        let count = CGImageSourceGetCount(gifSource)
        //把每一帧图片拼接到数组
        for i in 0...count-1 {
            guard let imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, nil) else { return }
            let image = UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up)
            images.append(image)
        }
    }
    
    private func displayGIF(_ duration: TimeInterval, _ repeatCount: Int) {
        self.animationImages = images
        self.animationDuration = duration
        self.animationRepeatCount = repeatCount
        self.startAnimating()
    }
    
}


最后


附上GitHub的传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,936评论 3 118
  • 十二月的中原初冬正浓,没有生机的庙坪山大眼望去全是枯草,黄土,落叶交织的棕黄,少平走在从县城到乡下的碎石路上,心中...
    L右右阅读 139评论 0 0
  • 今天又是高考的日子,对读书人来说,就是走出校门的终极考验。高考的基础是必须读书,不读书,怎会遇上这样的事? ...
    杨无涯阅读 133评论 0 0
  • 转载请注明出处:http://www.olinone.com/ 今天,跟大家聊聊“自释放”思想在iOS开发中的应用...
    张群阅读 300评论 0 2
  • 时常会闻到一种味道,温暖质朴,让人安心舒适。那是一种接近热的大麦茶浮出的香气,闻到这种味道时,总愿意闭上眼睛,微笑...
    April的秘密花园阅读 222评论 0 2