Using a hardware layer in onDraw custom view

So, I'm trying to figure out how I can correctly use hardware acceleration (when available) in a custom View that is constantly being animated. This is the basic premise of my onDraw() :

 canvas.drawColor(mBackgroundColor); for (Layer layer : mLayers) { canvas.save(); canvas.translate(layer.x, layer.y); //Draw that number of images in a grid, offset by -1 for (int i = -1; i < layer.xCount - 1; i++) { for (int j = -1; j < layer.yCount - 1; j++) { canvas.drawBitmap(layer.bitmap, layer.w * i, layer.h * j, null); } } //If the layer x has moved past its width, reset back to a seamless position layer.x += ((difference * layer.xSpeed) / 1000f); float xOverlap = layer.x % layer.w; if (xOverlap > 0) { layer.x = xOverlap; } //If the layer y has moved past its height, reset back to a seamless position layer.y += ((difference * layer.ySpeed) / 1000f); float yOverlap = layer.y % layer.h; if (yOverlap > 0) { layer.y = yOverlap; } canvas.restore(); } //Redraw the view ViewCompat.postInvalidateOnAnimation(this); 

I turned on the hardware levels in onAttachedToWindow() and disabled them in onDetachedFromWindow() , but I'm trying to figure out if I really use it. Essentially, the i/j loop that calls drawBitmap() never changes; the only thing that changes is the Canvas translation. Is Bitmap automatically saved on the GPU as a texture behind the scenes, or is there something I need to do manually to do this?

+8
performance android android-view hardware-acceleration
source share
2 answers

On which views do you set View.LAYER_TYPE_HARDWARE exactly? If you set the hardware level in a view that contains the drawing code shown above, you get the system to do a lot more work than necessary. Since you only draw raster images, you do not need anything here. If you call Canvas.drawBitmap() , the structure will cache the resulting OpenGL texture on your behalf.

However, you can optimize your code a bit more. Instead of calling drawBitmap() you can use child views. If you move these children using the offset*() (or setX() / setY() ) methods, the framework will apply further optimizations to avoid calling the draw() methods again.

In general, hardware layers should be installed on views that are expensive to attract and whose content will not change often (so it's almost the opposite of what you do :)

+6
source share

You can use the Android Tracer for OpenGL ES to find out if your view invokes OpenGL commands.

From developer.android.com

Tracer is an OpenGL code analysis tool for embedded systems (ES) in an Android application. The tool allows you to capture OpenGL ES commands and frame images to help you understand how your graphics commands are executed.

There is also an Android Performance Study tutorial from Romain Guy that describes its use almost step by step.

+1
source share

All Articles