SkBitmap is a very important class in skia. Many painting operations involve SkBitmap. It encapsulates a series of operations related to bitmap. understanding its memory management policy helps us better use it, it was intended to accelerate the hardware of blitter in skia.
1. SkBitmap class structure:
2. The nested class Allocator of SkBitmap
Allocator is an embedded class of SkBitmap. In fact, there is only one member function: allocPixelRef (). Therefore, it is more suitable to understand it as an interface. SkBitmap uses Allocator's derived class-HeapAllocator as its default distributor. The implementation is as follows:
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;
}
Of course, you can also define an Allocator by yourself. Use the member function allocPixels (Allocator * allocator, SkColorTable * ctable) of SkBitmap to pass in the Custom Allocator. If the input is NULL, the default HeapAllocator is used.
3. SkPixelRef class
SkPixelRef is closely related to Allocator. The memory allocated by Allocator is handled by SkPixelRef. Each Allocator corresponds to a SkPixelRef. Generally, Allocator calls setPixelRef to bind the allocated memory. By default, SkBitmap uses SkMallocPixelRef and HeapAllocator for pairing. Therefore, if you want to derive the Allocator class, you usually need to derive a SkPixelRef class that corresponds to it.
4. Example
The following is a short piece of code indicating how to dynamically allocate a SkBitmap:
SkBitmap bitmap;
Bitmap. setConfig (hasAlpha? SkBitmap: kARGB_8888_Config:
SkBitmap: kRGB_565_Config, width, height );
If (! Bitmap. allocPixels ()){
Return;
}
// ...... // Draw bitmap
//......
// Draw the image to the Canvas
Canvas-> drawBitmap (bitmap, SkFloatToScalar (x), SkFloatToScalar (y), paint );