Android Canvas and Hardware Acceleration?

neptune692 picture neptune692 · Feb 9, 2013 · Viewed 12.2k times · Source

Hi all I was wondering if it was possible to draw to an offscreen Canvas / Bitmap and take advantage of hardware acceleration or do I have to draw inside the onDraw() method of the View

For example I draw to an offscreen Bitmap by doing the following:

Bitmap.Config config = Bitmap.Config.ARGB_8888;
Bitmap buffer = Bitmap.createBitmap(200, 200, config);
Canvas canvas = new Canvas(buffer);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawLine(0, 0, 100, 100, paint);

However canvas.isHardwareAccelerated() returns false and drawing is sluggish compared to:

protected void onDraw(Canvas canvas) {

    Paint paint = new Paint();
    paint.setColor(Color.RED);

    canvas.drawLine(0, 0, 100, 100, paint);
}

where canvas.isHardwareAccelerated() returns true. Is there a way to draw to a Bitmap while taking advantage of hardware acceleration? Or do I have to draw directly to the screen in the onDraw method?

Thank you for your help :) I know in Java I can draw to a BufferedImage offscreen and it'll be hardware accelerated but maybe its not the same on a phone...

Answer

S.D. picture S.D. · Feb 9, 2013

Because in first case , you create the canvas, it is not backed up by a hardware layer. Also, as of now, you cannot enable HWA on just any Canvas, it must belong to an HWA View.

A view on the other hand, has access to system's hardware capabilities. You can use that by calling setLayerType( LAYER_TYPE_HARDWARE) as described in docs:

Indicates that the view has a hardware layer. A hardware layer is backed by a hardware specific texture (generally Frame Buffer Objects or FBO on OpenGL hardware) and causes the view to be rendered using Android's hardware rendering pipeline, but only if hardware acceleration is turned on for the view hierarchy. When hardware acceleration is turned off, hardware layers behave exactly as software layers.

Also, The performance concern applies more to the rendering part, and less to drawing. All draw operations are recorded as a Picture object. Its the rendering operation where HWA plays an important role.