How to set an image to fill a canvas

2019-05-18 08:47发布

问题:

I am trying to set a png image to fill the background of my canvas while still maintaining its aspect ratio. I start by converting it to a Bitmap:Then set the back ground using the setBitmap method from the Canvas class:

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);

}
}

But once I go to the Activity that calls this extended View class I get an error saying my application stopped unexpectedly. I've also tried playing around with some of the other functions in the Canvas and Bitmap class but nothing seems to work.

Please what is the best way to do this? I read on the android developer site that there is a way to set an image so that it is the canvas and other images can then be drawn inside it but I wasn't able to figure out how to do that.

Thanks!

回答1:

You might want to add a Log.d to check that the board bitmap returned from

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

isn't null. But I am using the following to draw bitmaps to full screen views in onDraw in several applications, so if the bitmap is non-null that should work fine.

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

And there's a version of drawBitmap which scales, namely

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

You might want to try that?