2011-05-04 32 views
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); 

} 
} 

但是,一旦我去调用这个扩展的查看I类活动得到一个错误,说我的应用程序意外停止。 我也尝试过在Canvas和Bitmap类中的其他一些功能,但似乎没有任何工作。

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

谢谢!

+0

发布您的应用程序在崩溃时说的logcat。 – JoxTraex 2011-05-04 23:03:22

回答

1

你可能要添加一个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. 

你可能想尝试吗?