歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android SkBitmap的內存管理分析

Android SkBitmap的內存管理分析

日期:2017/3/1 11:10:32   编辑:Linux編程

Android使用的2D圖形引擎skia,是一個高效的2D矢量圖形庫,google已經把skia開源:http://code.google.com/p/skia/

SkBitmap是skia中很重要的一個類,很多畫圖動作涉及到SkBitmap,它封裝了與位圖相關的一系列操作,了解它的內存管理策略有助於我們更好的使用它,了解它的初衷是要想實現對skia中的blitter進行硬件加速。

1. SkBitmap的類結構:


2. SkBitmap的內嵌類Allocator

Allocator是SkBitmap的內嵌類,其實只有一個成員函數:allocPixelRef(),所以把它理解為一個接口更合適,SkBitmap使用Allocator的派生類--HeapAllocator作為它的默認分配器。其實現如下:

bool SkBitmap::HeapAllocator::allocPixelRef(SkBitmap* dst,
SkColorTable* ctable) {
Sk64 size = dst->getSize64();
if (size.isNeg() || !size.is32()) {
return false;
}
void* addr = sk_malloc_flags(size.get32(), 0); // returns NULL on failure
if (NULL == addr) {
return false;
}
dst->setPixelRef(new SkMallocPixelRef(addr, size.get32(), ctable))->unref();
// since we're already allocated, we lockPixels right away
dst->lockPixels();
return true;
}

當然,也可以自己定義一個Allocator,使用SkBitmap的成員函數allocPixels(Allocator* allocator, SkColorTable* ctable) ,傳入自定義的Allocator即可,如果傳入NULL,則使用默認的HeapAllocator

3. SkPixelRef類

SkPixelRef和Allocator密切相關,Allocator分配的內存由SkPixelRef來處理引用計數,每個Allocator對應一個SkPixelRef,通常在分配內存成功後,由Allocator調用setPixelRef來進行綁定。默認的情況下,SkBitmap使用SkMallocPixelRef和HeapAllocator進行配對。所以如果你要派生Allocator類,通常也需要派生一個SkPixelRef類與之對應。

4. 使用例子

以下是一段簡短的代碼,示意如何動態分配一個SkBitmap:

SkBitmap bitmap;

bitmap.setConfig(hasAlpha ? SkBitmap::kARGB_8888_Config :
SkBitmap::kRGB_565_Config, width, height);
if (!bitmap.allocPixels()) {
return;
}

//......
// 對bitmap進行畫圖操作
//......
// 畫到Canvas上
canvas->drawBitmap(bitmap, SkFloatToScalar(x), SkFloatToScalar(y), paint);
Copyright © Linux教程網 All Rights Reserved