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

2019-01-24 00:28发布

问题:

Everytime I use this code nothing is drawn. I need to draw a bitmap inside of a specified rectangle.

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

I've looked online but can't find much help.

回答1:

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.



回答2:

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.



回答3:

I dont know why but this worked for me!

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

Thanks:)