Draw only a portion of Drawable / Bitmap

I was wondering if it is possible to draw only part of a bitmap after loading it into memory without creating a new Bitmap. I see that Drawable has a setBounds method, but I'm not sure if it only draws a region or just resizes the whole image. Thanks.

+6
android drawable bitmap surfaceview
source share
2 answers

Assuming you have a basic canvas for drawing, you can use one of the canvas's drawBitmap methods to draw a subset of the loaded bitmap.

public void drawBitmap (bitmap bitmap, Rect src, Rect dst, Paint for paint)

+9
source share

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) { // Empty } @Override public void setColorFilter(ColorFilter cf) { // Empty } @Override public int getOpacity() { return PixelFormat.OPAQUE; } public Bitmap getBitmap() { return bitmap; } } 
+2
source share

All Articles