Search code examples
androidgraphicsbitmapandroid-canvas

Using method -canvas.drawBitmap(bitmap, src, dst, paint)


I need to draw a bitmap inside of a specified rectangle. Why is it not drawn?

canvas.drawBitmap(MyBitmap, null, rectangle, null)

Solution

  • EDIT


    The original answer is incorrect. You can use the sourceRect to specify a part of a Bitmap to draw. It may be null, in which case the whole image will be used.

    As per the fryer comment he was drawing beneath something, I'll add a note on that.

    drawBitmap(bitmap, srcRect, destRect, paint) does not handle Z ordering (depth) and the order of calling draw on object matters.

    If you have 3 shapes to be drawn, square, triangle and circle. If you want the square to be on top then it must be drawn last.


    You're not specified any source, so its not drawn anything.

    Example:

    You have a Bitmap 100x100 pixels. You want to draw the whole Bitmap.

    canvas.drawBitmap(MyBitmap, new Rect(0,0,100,100), rectangle, null);
    

    You want to draw only the left half of the bitmap.

    canvas.drawBitmap(MyBitmap, new Rect(0,0,50,100), rectangle, null);
    

    You need to specify the source rect, the source rect can be a rectangle anywhere from 0,0 to the width,height of the bitmap.