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

牧云@^-^@ 提交于 2019-11-29 01:13:43
triggs

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.

The main item to remember when defining the Rect is:

  • left < right and top < bottom

The rect is in screen coordinates (positive Y downward) ...

I find it helpful to think of the Rect arguments

(left, top, right, bottom)

as

(X, Y, X + Width, Y + Height)

where X,Y is the top left corner of the sprite image.

NOTE: If want to center the image on a particular location, remember to offset those values by half the sprite width & height. For example:

int halfWidth = Width/2;
int halfHeight = Height/2
Rect dstRectForRender = new Rect( X - halfWidth, Y - halfHeight, X + halfWidth, Y + halfHeight );
canvas.drawBitmap ( someBitmap, null, dstRectForRender, null );

This uses the whole original image (since src rect is null) and scales it to fit the size and position from dstRectForRender ... and using the default Paint.

I dont know why but this worked for me!

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

Thanks:)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!