Home Ask Login Register

Developers Planet

Your answer is one click away!

user914425 February 2016

Adding BitMap Resource to Paint Object in Android

I have a Pain Object that I want to overlay a Bitmap from Android resources.

 public static Paint createPaint(int color, int strokeWidth, Style style) {
    Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
    return paint;

It is probably simple thing to do. I am not understanding Android paint, canvas, and bitmap relationships.


brindy February 2016

Paint objects are used to style canvas operations in the 'onDraw' method of a View. That canvas object lets you draw bitmaps directly to it. So if you wanted the bitmap as a background you could draw your bitmap first, then use the other canvas operations to draw on top using your configured Paint objects to style those drawing operations.

See View#onDraw() and the linked Canvas object in the API docs: http://developer.android.com/reference/android/view/View.html#onDraw(android.graphics.Canvas)

Other tips, avoid object allocation in the onDraw method. Create your Paint object(s) and load your Bitmaps elsewhere and keep a reference to them for use in your onDraw method.

Extremely simplistic example:

public class CustomView extends View {

    private Bitmap background;
    private Paint paint;
    private float size;

    public CustomView(Context context) {

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    public void init() {

        // Prepare your paint objects
        paint = new Paint();

        // Load your bitmap
        background = BitmapFactory.decodeResource(getResources(), R.drawable.waracle_square);

        // Calculate density dependant variables
        size = getResources().getDisplayMetrics().density * 100;


    protected void onDraw(Canvas canvas) {

        // The paint is optional when drawing an image
        canvas.drawBitmap(background, 0, 0, null);

        // red circle of size 100dp in top left corner

Post Status

Asked in February 2016
Viewed 3,820 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life