Using BitmapShader in Android

Recently I had to implement some custom UI controls for one of our customers, and some of these controls involved drawing Bitmaps with rounded corners.
Android provides a handy approach to this problem, all the magic can be done with a little help from a class named BitmapShader.

With BitmapShader you can draw bitmaps in any shape and even more, here’s an example:


What BitmapShaderdoes is basically providing a pixel source to a Paint object, when you draw something on a Canvasyou have to specify the Paintinstance that will be used to paint your stuff, if that Paintis bound to a BitmapShader you’ll get your stuff painted using the Bitmap that the BitmapShaderwas created with.

Here’s how to create a BitmapShaderobject:

With the BitmapShaderin place you can now draw anything you want using a Paint which is bound to the shader, the binding can be achieved with the setShader() method of the Paint class:

Now everything is in place and you can start drawing your bitmaps, following is a list of what I did in the example screenshot above and the code I used to achieve each sample, also note that in order to draw on a Canvas I created a custom View subclass and I added the drawing code inside the onDraw() method, in a real scenario however try to avoid allocating stuff inside the onDraw() method.

Rounded corners


Bottom corners rounded


Top corners rounded




Narrow oval


Wide oval