2

我正在尝试设置一个 png 图像来填充画布的背景,同时仍保持其纵横比。我首先将其转换为位图:然后使用 Canvas 类中的 setBitmap 方法设置背景:

http://developer.android.com/reference/android/graphics/Canvas.html#Canvas(android.graphics.Bitmap )

public class PlayOn extends View{

Bitmap board;

public PlayOn(Context gamecontext)  {
    super(gamecontext);             
    board=BitmapFactory.decodeResource(getResources(),R.drawable.board_rev1);
}

@Override
protected void onDraw(Canvas mycanvas) {

    super.onDraw(mycanvas);
    mycanvas.setBitmap(board);

}
}

但是,一旦我转到调用此扩展视图类的 Activity,我就会收到一条错误消息,说我的应用程序意外停止。我也尝试过使用 Canvas 和 Bitmap 类中的其他一些函数,但似乎没有任何效果。

请问最好的方法是什么?我在 android 开发者网站上读到有一种方法可以设置图像,使其成为画布,然后可以在其中绘制其他图像,但我无法弄清楚如何做到这一点。

谢谢!

4

1 回答 1

2

您可能需要添加 Log.d 以检查板位图是否从

BitmapFactory.decodeResource(getResources(),R.drawable.board_rev1); 

不为空。但是我在几个应用程序中使用以下内容在 onDraw 中将位图绘制到全屏视图,所以如果位图不为空,那应该可以正常工作。

canvas.drawBitmap(mBitmap, 0, 0, null);

还有一个可缩放的drawBitmap版本,即

void canvas.drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
Draw the specified bitmap, scaling/translating automatically to fill the 
destination rectangle.

你可能想试试?

于 2011-05-05T01:08:21.143 回答