我需要在指定的矩形内绘制位图。为什么没有画出来?
canvas.drawBitmap(MyBitmap, null, rectangle, null)
编辑
原答案不正确。 您可以使用 sourceRect 指定要绘制的位图的一部分。 它可能为空,在这种情况下将使用整个图像。
根据他在某物下方绘制的油炸锅评论,我将对此添加注释。
drawBitmap(bitmap, srcRect, destRect, paint)
不处理 Z ordering (depth)
和调用绘制对象的顺序。
如果你有3种形状要画,正方形,三角形和圆形。如果你想让正方形在上面,那么它必须最后绘制。
你没有指定任何来源,所以它没有绘制任何东西。
例子:
你有一个 100x100 像素的位图。你想绘制整个位图。
canvas.drawBitmap(MyBitmap, new Rect(0,0,100,100), rectangle, null);
你只想绘制位图的左半部分。
canvas.drawBitmap(MyBitmap, new Rect(0,0,50,100), rectangle, null);
您需要指定源矩形,源矩形可以是从 0,0 到位图的宽度、高度的任意矩形。
定义 Rect 时要记住的主要项目是:
矩形在屏幕坐标中(正 Y 向下)...
我发现考虑 Rect 参数很有帮助
(left, top, right, bottom)
作为
(X, Y, X + Width, Y + Height)
其中 X,Y 是精灵图像的左上角。
注意:如果要将图像居中放置在特定位置,请记住将这些值偏移精灵宽度和高度的一半。例如:
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 );
这使用整个原始图像(因为 src rect 为空)并缩放它以适应 dstRectForRender 的大小和位置......并使用默认的 Paint.
这对我有用!
Rect rectangle = new Rect(0,0,100,100);
canvas.drawBitmap(bitmap, null, rectangle, null);