說說WebP
WebP說白了就是一種新的圖片格式(其實也推出好久了),由谷歌研發(fā),在安卓上的支持也蠻好的,從安卓4.0開始就已經(jīng)原生支持了,但在iOS系統(tǒng)上,還是需要我們做些特殊處理的。關(guān)于WebP的種種好處和不好處,我就不細說了,看看一些關(guān)于WebP的介紹文章就行 https://isux.tencent.com/introduction-of-webp.html ,然后谷歌最近又在捅咕新的幺蛾子 http://www.elecfans.com/rengongzhineng/475356.html 。
我們需要做什么
主要是兩大點:
1、WebP圖片的下載及展示
2、UIWebView中展示W(wǎng)ebP圖片
圖片的下載及展示
首先說一下圖片的展示,在iOS項目中最常用的圖片加載庫,肯定是SDWebImage,如何讓SDWebImage支持WebP格式的圖片的加載呢?很簡單:
1、首先在項目設(shè)置中加入SDWebImage支持WebP的宏 SD_WEBP=1 :
Paste_Image.png
2、這個宏就是告訴讓SDWebImage支持WebP圖片加載的宏,但是,如果你的SDWebImage是在CocoaPods中集成的,那么不好意思,項目中的宏在CocoaPods中是不生效的,所以我們,將CocoaPods中的SDWebImage移除,然后,直接將SDWebImage拖到項目中,這里需要注意的是,你在Git上的SDWebImage項目,里面一定要包含了UIImage+WebP這個分類。
Paste_Image.png
以上,SDWebImage就支持WebP圖片的加載了。
當(dāng)然,如果我們是自己處理的一些圖片加載呢?比如[UIImage imageWithData:[NSData dataWithContentOfUrl:@"www.www.com.cn"]]這種呢,這種我們下載下來的NSData所構(gòu)成的圖片格式,就是WebP的了,想轉(zhuǎn)換為UIIImage是沒法的了,這里推薦一個比較好用的轉(zhuǎn)換格式的庫,YYImage,這個庫默認不支持WebP,需要加入更多的組件,Pod集成如下:
pod 'YYImage'
pod 'YYImage/WebP'
這樣,我們就可以將NSData正常轉(zhuǎn)換為UIImage了,不管NSData里的數(shù)據(jù)是什么格式的:
YYImageDecoder *decoder = [YYImageDecoder decoderWithData:imageData scale:2.0];
UIImage *image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
再來說下UIWebView
UIWebView默認不支持WebP格式的圖片加載,這里我們需要攔截圖片的URL,這里我們可以使用NSURLProtocol進行攔截,但自己寫還是比較麻煩的,這里推薦一個寫好的:WebpForUIWebView
用法:
Step 1: Drop [WEBPURLProtocol.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.h) and [WEBPURLProtocol.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.m) into your project, Swift or ObjC.
Step 2: If you didn't have a WebP decoder already in your project. Drop [WebP.framework](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/WebP.framework), [UIImage+Webp.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/UIImage%2BWebP.h),[UIImage+Webp.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/UIImage%2BWebP.m), [WEBPDemoDecoder.h](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPDemoDecoder.h), [WEBPDemoDecoder.m](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPDemoDecoder.m) into your project. If you already have a WebP decoder in your project, create a new class that conforms to [WEBPURLProtocolDecoder](https://github.com/8BADBEEF/WebpForUIWebView/blob/master/Webp/WEBPURLProtocol.h#L5) using the existing decoder.
Step 3: Whenever you are in the mood for rendering WebP in UIWebView, start the engine with the following code:
[WEBPURLProtocol registerWebP:/*An instance of any class that conforms to WEBPURLProtocolDecoder*/];
All done.
以上,WebP的支持就OK了。