Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android drawBitmap 5x performance difference

I've been fighting with android performance all night and possibly solved the issue I've been dealing with, however I'm still very confused and could use some help. Consider the timing differences between these two samples.

The first sample loads in a drawable bitmap and creates a mutable copy of it

Bitmap cacheBitmap;
Canvas cacheCanvas;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (cacheBitmap != null) {
        cacheBitmap.recycle();
    }
    Resources res = getContext().getResources();
    Bitmap blankImage = BitmapFactory.decodeResource(res, R.drawable.blank);

    /* copy existing bitmap */
    cacheBitmap = Bitmap.createScaledBitmap(blankImage, w, h, false);
    /* copy existing bitmap */

    cacheCanvas = new Canvas();
    cacheCanvas.setBitmap(cacheBitmap);
    cacheCanvas.drawRGB(255, 255, 255);
}
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(cacheBitmap, 0, 0, null); // draws in 7-8 ms
}

The second sample creates a new bitmap without copying the original blank image.

Bitmap cacheBitmap;
Canvas cacheCanvas;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (cacheBitmap != null) {
        cacheBitmap.recycle();
    }
    Resources res = getContext().getResources();
    Bitmap blankImage = BitmapFactory.decodeResource(res, R.drawable.blank);

    /* create fresh bitmap */
    cacheBitmap = Bitmap.createBitmap(w, h, blankImage.getConfig());
    /* create fresh bitmap */

    cacheCanvas = new Canvas();
    cacheCanvas.setBitmap(cacheBitmap);
    cacheCanvas.drawRGB(255, 255, 255);
}
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(cacheBitmap, 0, 0, null); // draws in 40 ms
}

The first sample draws 5-6 times faster then the second sample, why is this? I'd like to be able to write this code in some way that doesn't even rely on the blank image, but no matter what I do I end up with a slow bitmap draw without having it available to copy initially.

like image 531
seanalltogether Avatar asked Aug 09 '11 00:08

seanalltogether


1 Answers

Check the format of the bitmap. In older versions of Android, there was a bug (feature?) that would always use 565 for bitmaps without alpha and 8888 for bitmaps with alpha when creating the bitmap using certain functions.

I'm tempted to say that somehow one version uses 8888 while the other one uses 565, giving you the speed gain.

Use getConfig to investigate both bitmaps.

like image 141
EboMike Avatar answered Sep 26 '22 20:09

EboMike