swift-Gif動畫和JSON動畫分析

項目中使用動畫,開始采用Gif動畫,發(fā)現(xiàn)Gif動畫文件1.5M 在線加載慢登夫,改為json動畫使用Lottie 第三方庫加載對比分析,優(yōu)缺點分析主要兩點:

1.json文件只有400k 對比gif文件包少了三分之二 蝗敢;

2.UI效果對比gif顯示放大有齒輪和鏤空的失真日缨,json動畫UI還原度高,但是json動畫設(shè)計轉(zhuǎn)出json文件更麻煩些家卖;

場景分析:

1.gif動畫適合小圖標(biāo)動畫效果

2.json動畫適合大圖動畫效果

Gif demo代碼片段

/// 顯示本地 GIF 圖片

? ? func showLocalGIF(name: String?) {

? ? ? ? guard?let?name = name?else?{?return?}

? ? ? ? self.gifImage=GIFImage(named: name)

? ? }

json 動畫代碼實例盆犁,采用pod 'lottie-ios', '3.2.3'版本 ?,本地json文件顯示動畫:

let animationView = AnimationView(name: "inviteData")

? ? ? ? animationView.frame = CGRect(x: 0, y: 0, width: (kScreenWidth - 80)*kWidthScale, height:((kScreenWidth - 80)*1225/879)*kWidthScale)

? ? ? ? imageBackVIew.addSubview(animationView)

? ? ? ? animationView.contentMode = .scaleToFill

? ? ? ? animationView.loopMode = .loop

? ? ? ? animationView.play()

? ? ? ? animationView.play { (isFinished) in

?? ? ? ?}

在線加載json文件采用兩種方式:

一、在線加載json文件,采用pod 'lottie-ios', '3.2.3'版本 ?網(wǎng)頁可直接打卡json文件:

if let url = URL(string: "https://yangtuo.oss-cn-hangzhou.aliyuncs.com/mall2c/happy_gift.json") {

????????giftAnimaView = AnimationView(url: url, imageProvider: self, closure: { [weak self] (error) in

?????????????guard let `self` = self else { return }

? ? ? ? ? ? ? ? if let _ = error {

? ? ? ? ? ? ? ? ? ? print("網(wǎng)絡(luò)動畫加載失敗~~")

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? /// 獲取是異步的篡九,所以需要等待動畫獲取完成

? ? ? ? ? ? ? ? ? ? self.giftAnimaView.play { (finished) in

????????????????}

??}

? ? ? ? ? ? ? ? }, animationCache: self)

? ? ? ? ? ? giftAnimaView.frame = CGRect(x: 0, y: 0, width: (kScreenWidth - 80)*kWidthScale, height:((kScreenWidth - 80)*1225/879)*kWidthScale)

? ? ? ? ? ? giftAnimaView.contentMode = .scaleToFill

? ? ? ? ? ? giftAnimaView.loopMode = .loop

? ? ? ? ? ? imageBackVIew.addSubview(giftAnimaView)

? ? ? ? }


二谐岁、在線加載json文件,采用pod 'lottie-ios', '3.2.3'版本 ?需下載json文件:

LPLottieResourceManager.shared.loadBundleProvider(123412,"\(BackGround)") {[weakself] (jsonpath, provider)in

?? ? ? ? ? ? guard?let`self` =self?else{return}

?? ? ? ? ? ? guard?let? jsonfile = json path?else{return}

? ? ? ? ? ? DeLog("jsonFile:\(jsonfile)")

?? ? ? ? ? ? self.giftAnimaView=AnimationView.init(filePath:jsonfile)

? ? ? ? ? ? ?iflet? prov = provider {

?? ? ? ? ? ? ? ? self.giftAnimaView.imageProvider= prov

?? ? ? ? ? ? }


? ? ? ? ? ? self.giftAnimaView.frame = CGRect(x: 0, y: 0, width: (kScreenWidth - 80)*kWidthScale, height:((kScreenWidth - 80)*1225/879)*kWidthScale)

? ? ? ? ? ? self.giftAnimaView.contentMode = .scaleToFill

? ? ? ? ? ? self.giftAnimaView.loopMode = .loop

? ? ? ? ? ? self.giftAnimaView.play()

? ? ? ? ? ? self.imageBackVIew.addSubview(self.giftAnimaView)

?? ? ? ? }


LPLottieResourceManager 類繼承NSObject,實現(xiàn)思路先通過Moya下載本地資源包,通過資源包打卡在線加載:

importUIKit

importFoundation

//import ZipArchive

import Moya

importLottie

typealiaslottieResultBlock= (_ jsonfullpath:String?,_ provider:BundleImageProvider?) ->Void

class LPLottieResourceManager:NSObject {

? ? let? filepath? =NSHomeDirectory() + "/Documents/LiveKit/GiftFile"

? ? static? let? shared = LPLottieResourceManager()

? ? override init() {

? ? ? ? super.init()

? ? ? ? ifFileManager.default.fileExists(atPath:filepath) {

? ? ? ? ? ? print("禮物 目錄存在")

? ? ? ? }

? ? ? ? else{

? ? ? ? ? ? try! FileManager.default.createDirectory(atPath: filepath,

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? withIntermediateDirectories:true,attributes:nil)

? ? ? ? }

? ? }

? ? /// 加載lottie特效

? ? /// - Parameters:

? ? ///? - giftId: 特效id

? ? ///? - downloadurl: 特效下載地址

? ? ///? - animationresult: 特效 images目錄

? ? func? loadBundleProvider(_giftId:Int,_downloadurl:String,_animationresult:@escapinglottieResultBlock) {

? ? ? ? letfullpath =filepath+"/\(giftId)/data.json"

? ? ? ? letimgprovider =filepath+"/\(giftId)/images"

? ? ? ? varjsonpath:String?=nil

? ? ? ? ifFileManager.default.fileExists(atPath: fullpath) {

? ? ? ? ? ? jsonpath = fullpath

? ? ? ? ? ? if? FileManager.default.fileExists(atPath: imgprovider)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? let? provider =BundleImageProvider.init(bundle:Bundle.main,searchPath: imgprovider)

? ? ? ? ? ? ? ? animationresult(jsonpath,provider)

? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? animationresult(jsonpath,nil)

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? ? ? //網(wǎng)絡(luò)下載 并解壓

? ? ? ? else{

? ? ? ? ? ? let? giftpath =filepath+"/\(giftId)"

? ? ? ? ? ? letassetName =? "\(giftId)"

? ? ? ? ? ? jsonpath = giftpath +"/data.json"

? ? ? ? ? ? let? urladdress? = downloadurl

? ? ? ? ? ? //通過Moya進行下載

? ? ? ? ? ? MyServiceProvider.request(.downloadGiftLottie(downloadurl:urladdress,giftDirectoryName: assetName)) { result in

? ? ? ? ? ? ? ? switchresult {

? ? ? ? ? ? ? ? case.success:

? ? ? ? ? ? ? ? ? ? letlocalLocation:URL= DefaultDownloadDir.appendingPathComponent(assetName)

? ? ? ? ? ? ? ? ? ? print("下載完畢伊佃!保存地址:\(localLocation)")

? ? ? ? ? ? ? ? ? ? if? urladdress.contains(".zip") {

? ? ? ? ? ? ? ? ? ? ? ? let? urlpath =URL.init(fileURLWithPath:self.filepath+"/\(giftId).zip")

? ? ? ? ? ? ? ? ? ? ? ? do{

? ? ? ? ? ? ? ? ? ? ? ? ? ? try? ? ? FileManager.default.createDirectory(atPath:self.filepath+"/\(giftId)",withIntermediateDirectories:true,attributes:nil)

? ? ? ? ? ? ? ? ? ? ? ? ? ? //得到正確的資源包? 12312/ data images

? ? ? ? ? ? ? ? ? ? ? ? ? ? if? FileManager.default.fileExists(atPath: imgprovider)

? ? ? ? ? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? let? provider =BundleImageProvider.init(bundle:Bundle.main,searchPath: imgprovider)

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? animationresult(jsonpath,provider)

? ? ? ? ? ? ? ? ? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? animationresult(jsonpath,nil)

? ? ? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? ? ? //? ? ? ? ? ? ? ? ? ? ? ? print(zipurl)

? ? ? ? ? ? ? ? ? ? ? ? }catch(leterr) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? print("解壓失敗")

? ? ? ? ? ? ? ? ? ? ? ? ? ? animationresult(nil,nil)

? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? elseifurladdress.contains(".json") {

? ? ? ? ? ? ? ? ? ? ? ? do{

? ? ? ? ? ? ? ? ? ? ? ? ? ? try? ? ? FileManager.default.createDirectory(atPath:self.filepath+"/\(giftId)",withIntermediateDirectories:true,attributes:nil)

? ? ? ? ? ? ? ? ? ? ? ? ? ? try? FileManager.default.moveItem(atPath:self.filepath+"/data.json",toPath: giftpath +"/data.json")

? ? ? ? ? ? ? ? ? ? ? ? ? ? animationresult(jsonpath,nil)

? ? ? ? ? ? ? ? ? ? ? ? }catch(leterr) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? debugPrint("文件出錯\(err)")

? ? ? ? ? ? ? ? ? ? ? ? ? ? animationresult(nil,nil)

? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ??caselet.failure(error):

? ? ? ? ? ? ? ? ? ? print(error)

? ? ? ? ? ? ? ? ? ? animationresult(nil,nil)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? }

}

//MARK:單獨組件處理下載

//初始化請求的provider

let MyServiceProvider = MoyaProvider<DownLoadService>()

//請求分類

public enum DownLoadService {

? ? casedownloadGiftLottie(downloadurl:String,giftDirectoryName:String)//下載文件

}

//請求配置

extension DownLoadService: TargetType {

? ? publicvarpath:String{

? ? ? ? return""

? ? }

? ? //服務(wù)器地址

? ? publicvarbaseURL:URL{

? ? ? ? switchself{

? ? ? ? case.downloadGiftLottie(let? url , _ ):

? ? ? ? ? ? returnURL.init(string: url)!

? ? ? ? default:

? ? ? ? ? ? return URL(string: "http://www.baidu.com")!

? ? ? ? }

? ? }

? ? //請求類型

? ? publicvarmethod: Moya.Method{

? ? ? ? return.get

? ? }

? ? //請求任務(wù)事件(這里附帶上參數(shù))

? ? publicvartask:Task{

? ? ? ? switchself{

? ? ? ? case.downloadGiftLottie(let? downloadurl ,letsaveName):

? ? ? ? ? ? varlocalLocation:URL!

? ? ? ? ? ? ifdownloadurl.contains(".zip") {

? ? ? ? ? ? ? ? localLocation = DefaultDownloadDir.appendingPathComponent(saveName+".zip")

? ? ? ? ? ? }elseifdownloadurl.contains(".json") {


? ? ? ? ? ? ? ? localLocation = DefaultDownloadDir.appendingPathComponent("data.json")

? ? ? ? ? ? }

? ? ? ? ? ? //


? ? ? ? ? ? letdownloadDestination:DownloadDestination= { _, _in


? ? ? ? ? ? ? ? return(localLocation, .removePreviousFile) }

? ? ? ? ? ? return.downloadDestination(downloadDestination)

? ? ? ? }


? ? }


? ? //是否執(zhí)行Alamofire驗證

? ? public?var?validate:Bool{

? ? ? ? return false

? ? }


? ? //這個就是做單元測試模擬的數(shù)據(jù)窜司,只會在單元測試文件中有作用

? ? public?var?sampleData:Data{

? ? ? ? return"{}".data(using:String.Encoding.utf8)!

? ? }


? ? //請求頭

? ? publicvarheaders: [String:String]? {

? ? ? ? returnnil

? ? }

}

//定義下載的DownloadDestination(不改變文件名,同名文件不會覆蓋)

privateletDefaultDownloadDestination:DownloadDestination= { temporaryURL, responsein

? ? return(DefaultDownloadDir.appendingPathComponent(response.suggestedFilename!), [.removePreviousFile])

}

//默認(rèn)下載保存地址(用戶文檔目錄)

let DefaultDownloadDir: URL = {

? ? return? URL(fileURLWithPath: LPLottieResourceManager.shared.filepath)

}()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末航揉,一起剝皮案震驚了整個濱河市塞祈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌帅涂,老刑警劉巖议薪,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異媳友,居然都是意外死亡斯议,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門醇锚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哼御,“玉大人,你說我怎么就攤上這事焊唬×抵纾” “怎么了?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵赶促,是天一觀的道長液肌。 經(jīng)常有香客問我,道長鸥滨,這世上最難降的妖魔是什么矩屁? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮爵赵,結(jié)果婚禮上吝秕,老公的妹妹穿的比我還像新娘。我一直安慰自己空幻,他們只是感情好烁峭,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著秕铛,像睡著了一般约郁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上但两,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天鬓梅,我揣著相機與錄音,去河邊找鬼谨湘。 笑死绽快,一個胖子當(dāng)著我的面吹牛芥丧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播坊罢,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼续担,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了活孩?” 一聲冷哼從身側(cè)響起物遇,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎憾儒,沒想到半個月后询兴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡起趾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年诗舰,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片阳掐。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡始衅,死狀恐怖冷蚂,靈堂內(nèi)的尸體忽然破棺而出缭保,到底是詐尸還是另有隱情,我是刑警寧澤蝙茶,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布艺骂,位于F島的核電站,受9級特大地震影響隆夯,放射性物質(zhì)發(fā)生泄漏钳恕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一蹄衷、第九天 我趴在偏房一處隱蔽的房頂上張望忧额。 院中可真熱鬧,春花似錦愧口、人聲如沸睦番。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽托嚣。三九已至,卻和暖如春厚骗,著一層夾襖步出監(jiān)牢的瞬間示启,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工领舰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留夫嗓,地道東北人迟螺。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像啤月,于是被迫代替她去往敵國和親煮仇。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容