Android 在画布上绘制缩放位图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10407089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:35:31  来源:igfitidea点击:

Draw a scaled bitmap to the canvas?

android

提问by tadamson

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

... 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?

我的问题是,我如何设置它来绘制以“位图缩放”形式返回的缩放位图,而不是原始位图?

回答by epichorns

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

定义一个新的类成员变量: Bitmap mScaledBackground;然后,将新创建的缩放位图分配给它: mScaledBackground = scaled;然后,调用 draw 方法: c.drawBitmap(mScaledBackground, 0, 0, null);

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

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:

并且最好不要为了以缩放方式绘制原始背景的唯一目的而声明新位图。位图会消耗大量宝贵的资源,通常手机只能加载几 mb 的位图,您可以在应用程序异常失败之前加载它。相反,您可以执行以下操作:

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

回答by sebsebmc

To draw the scaled bitmap you want save your scaled bitmap in a field somewhere (here called mScaled) and call:

要绘制缩放位图,您希望将缩放位图保存在某个字段中(此处称为 mScaled)并调用:

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

in your draw method (or wherever you call it right now).

在您的 draw 方法(或您现在调用它的任何地方)中。