I was looking for an answer to this question to be able to reuse existing bitmaps for my image cache and avoid memory fragmentation (and subsequent OutOfMemoryError ...), which was caused by a lot of bitmaps allocated in different parts of memory space. As a result, I created a simple specialized "BitmapSubsetDrawable" that expands itself as an arbitrary part of the underlined bitmap (the part is determined by scrRect). Now I select a set of large enough Bitmaps once, and then reuse them (canvas.drawBitmap (sourceBitmap, 0, 0, null), on them ...) to store various bitmaps.
Below is the main class code, see BitmapSubsetDrawable.java for actual use.
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; public class BitmapSubsetDrawable extends Drawable { private Bitmap bitmap; private Rect scrRect; public BitmapSubsetDrawable(@NonNull Bitmap bitmap, @NonNull Rect srcRect) { this.bitmap = bitmap; this.scrRect = srcRect; } @Override public int getIntrinsicWidth() { return scrRect.width(); } @Override public int getIntrinsicHeight() { return scrRect.height(); } @Override public void draw(Canvas canvas) { canvas.drawBitmap(bitmap, scrRect, getBounds(), null); } @Override public void setAlpha(int alpha) {
yvolk
source share