绘制位图缩放到画布?位图、画布、缩放

由网友(幸福的距離)分享简介:下面code定义我的位图:The following code defines my bitmap:Resources res = context.getResources();mBackground = BitmapFactory.decodeResource(res,R.drawable.bg2);//scal...

下面code定义我的位图:

The following code defines my bitmap:

Resources res = context.getResources();

    mBackground = BitmapFactory.decodeResource(res,
            R.drawable.bg2);

    //scale bitmap
    int h = 800; // height in pixels
    int w = 480; // width in pixels    
    Bitmap scaled = Bitmap.createScaledBitmap(mBackground, w, h, true); // Make sure w and h are in the correct order

...而下面的code用于执行/绘制(未缩放的位图):

... And the following code is used to execute/draw it (the unscaled bitmap):

c.drawBitmap(mBackground, 0, 0, null);

我的问题是,如何才能将其设置为绘制缩放位图的形式返回位图缩放,而不是原来的?

My question is, how might I set it to draw the scaled bitmap returned in the form of "Bitmap scaled," and not the original?

推荐答案

定义一个新的类成员变量: 位图mScaledBackground; 然后,分配新创建的缩放位图吧: mScaledBackground =缩放; 然后,请致电您的抽奖方式: c.drawBitmap(mScaledBackground,0,0,NULL);

Define a new class member variable: Bitmap mScaledBackground; Then, assign your newly created scaled bitmap to it: mScaledBackground = scaled; Then, call in your draw method: c.drawBitmap(mScaledBackground, 0, 0, null);

请注意,这不是硬code屏幕尺寸,你在你的代码片段做上面的方法是一个好主意。更好是将取设备屏幕大小以下列方式:

Note that it is not a good idea to hard-code screen size in the way you did in your snippet above. Better would be to fetch your device screen size in the following way:

int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();

和这将是可能会更好不申报新位图绘制的原始背景的缩放方式的唯一目的。位图消耗了大量的precious资源,而且通常一个电话是有限的位图的几MB,你可以在你的应用程序非正常失败加载。相反,你可以做这样的事情:

And it would be probably better not to declare a new bitmap for the only purpose of drawing your original background in a scaled way. Bitmaps consume a lot of precious resources, and usually a phone is limited to a few mb of bitmaps you can load before your app ungracefully fails. Instead you could do something like this:

Rect src = new Rect(0,0,bitmap.getWidth()-1, bitmap.getHeight()-1);
Rect dest = new Rect(0,0,width-1, height-1);
c.drawBitmap(mBackground, src, dest, null);
阅读全文

相关推荐

最新文章