绘制位图缩放到画布? [英] Draw a scaled bitmap to the canvas?

查看:143
本文介绍了绘制位图缩放到画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于绘制位图缩放到画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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