如何设置图像填充画布 [英] How to set an image to fill a canvas

查看:270
本文介绍了如何设置图像填充画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设定一个PNG图像,以填补我的画布的背景下,同时仍保持其纵横比。我首先将其转换为位图:然后用setBitmap方法从Canvas类设置回地面:

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:

<一个href="http://developer.android.com/reference/android/graphics/Canvas.html#Canvas(android.graphics.Bitmap" rel="nofollow">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.

请什么是做到这一点的最好方法是什么?我读的Andr​​oid开发者网站,有一种方法,使其在画布和其他图像可以在它里面得出,但我无法弄清楚如何做到这一点,设置图像。

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.

谢谢!

推荐答案

您可能要添加一个Log.d来检查板位图,从

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

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

不为空。但我用下面的绘制位图到全屏视图的OnDraw在多个应用程序,因此,如果位图非空,应该很好地工作。

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

还有一个版本drawBitmap的案秤,即

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.

您可能想尝试的?

这篇关于如何设置图像填充画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆