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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With