圖片加載的工作流
- 1.假設我們使用 +imageWithContentsOfFile: 方法從磁盤中加載一張圖片,這個時候的圖片并沒有解壓縮;
- 2.然后將生成的 UIImage 賦值給 UIImageView ;
- 3.接著一個隱式的 CATransaction 捕獲到了 UIImageView 圖層樹的變化;
- 4.在主線程的下一個 run loop 到來時,Core Animation 提交了這個隱式的 transaction ,這個過程可能會對圖片進行 copy 操作,而受圖片是否字節對齊等因素的影響,這個 copy 操作可能會涉及以下部分或全部步驟:
a.分配內存緩沖區用于管理文件 IO 和解壓縮操作;
b.將文件數據從磁盤讀到內存中;
c.將壓縮的圖片數據解碼成未壓縮的位圖形式,這是一個非常耗時的 CPU 操作;
d.最后 Core Animation 使用未壓縮的位圖數據渲染 UIImageView 的圖層
在上面的步驟中,我們提到了圖片的解壓縮是一個非常耗時的 CPU 操作,并且它默認是在主線程中執行的。那么當需要加載的圖片比較多時,就會對我們應用的響應性造成嚴重的影響,尤其是在快速滑動的列表上,這個問題會表現得更加突出。
為什么需要解壓縮
位圖:位圖就是一個像素數組,數組中的每個像素就代表著圖片中的一個點。我們應用中經常用的png和jpeg就是位圖,都是一種壓縮的位圖圖形格式。
解壓縮后的圖片大小 = 圖片的像素寬 30 * 圖片的像素高 30 * 每個像素所占的字節數 4
在磁盤中的圖片渲染到屏幕之前,必須得到原始的圖片像素數據,這就是為什么要對圖片進行解壓縮操作。
強制解壓縮的原理
/* Create a bitmap context. The context draws into a bitmap which is `width'
pixels wide and `height' pixels high. The number of components for each
pixel is specified by `space', which may also specify a destination color
profile. The number of bits for each component of a pixel is specified by
`bitsPerComponent'. The number of bytes per pixel is equal to
`(bitsPerComponent * number of components + 7)/8'. Each row of the bitmap
consists of `bytesPerRow' bytes, which must be at least `width * bytes
per pixel' bytes; in addition, `bytesPerRow' must be an integer multiple
of the number of bytes per pixel. `data', if non-NULL, points to a block
of memory at least `bytesPerRow * height' bytes. If `data' is NULL, the
data for context is allocated automatically and freed when the context is
deallocated. `bitmapInfo' specifies whether the bitmap should contain an
alpha channel and how it's to be generated, along with whether the
components are floating-point or integer. */
CG_EXTERN CGContextRef __nullable CGBitmapContextCreate(void * __nullable data,
size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow,
CGColorSpaceRef cg_nullable space, uint32_t bitmapInfo)
CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);
看看 CGBitmapContextCreate
函數中每個參數所代表的具體含義:
- data :如果不為 NULL,那么它應該指向一塊大小至少為 bytesPerRow * height 字節的內存;如果 為 NULL
,那么系統就會為我們自動分配和釋放所需的內存,所以一般指定 NULL 即可; - width 和 height:位圖的寬度和高度,分別賦值為圖片的像素寬度和像素高度即可;
- bitsPerComponent :像素的每個顏色分量使用的 bit 數,在 RGB 顏色空間下指定 8 即可;
- bytesPerRow:位圖的每一行使用的字節數,大小至少為 width * bytes per pixel 字節。有意思的是,當我們指定 0 時,系統不僅會為我們自動計算,而且還會進行 cache line alignment 的優化,更多信息可以查看 what is byte alignment (cache line alignment) for Core Animation? Why it matters? 和 Why is my image’s Bytes per Row more than its Bytes per Pixel times its Width? ,親測可用;
- space :就是我們前面提到的顏色空間,一般使用 RGB 即可;
- bitmapInfo :就是我們前面提到的位圖的布局信息。
開源庫的實現
首先,我們來看看 YYKit 中的相關代碼,用于解壓縮圖片的函數 YYCGImageCreateDecodedCopy
存在于 YYImageCoder 類中,核心代碼如下:
CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay) {
...
if (decodeForDisplay) { // decode with redraw (may lose some precision)
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask;
BOOL hasAlpha = NO;
if (alphaInfo == kCGImageAlphaPremultipliedLast ||
alphaInfo == kCGImageAlphaPremultipliedFirst ||
alphaInfo == kCGImageAlphaLast ||
alphaInfo == kCGImageAlphaFirst) {
hasAlpha = YES;
}
// BGRA8888 (premultiplied) or BGRX8888
// same as UIGraphicsBeginImageContext() and -[UIView drawRect:]
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
//使用 CGBitmapContextCreate 函數創建一個位圖上下文
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), bitmapInfo);
if (!context) return NULL;
//使用 CGContextDrawImage 函數將原始位圖繪制到上下文中;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); // decode
//使用 CGBitmapContextCreateImage 函數創建一張新的解壓縮后的位圖
CGImageRef newImage = CGBitmapContextCreateImage(context);
CFRelease(context);
return newImage;
} else {
...
}
}