在canvas.drawBitmap中使用dpi替代像素

3
我已经阅读了“屏幕支持API指南”(http://developer.android.com/guide/practices/screens_support.html)和其他许多资源,但我无法理解dpi是如何工作的。
我正在开发一款游戏,没有使用任何布局(我将使用像canvas.drawbitmap这样的函数自己绘制所有内容)。但是当我使用Canvas.Drawbitmap函数时,我需要指定要绘制图像的屏幕像素。
所以我现在正在使用固定分辨率(1280x800),并使用drawable-nodpi文件夹,在稍后调整画布,如果手机屏幕更宽或更窄。问题是,当分辨率不是本机分辨率(1280x800)时,图像看起来很糟糕。
我该怎么做才能解决这个问题?我已经阅读了3天,但所有的解释和示例都与布局、九宫格等有关。

你尝试过创建一个函数,用于将dpi转换为像素吗?这样你就可以处理所有可用的分辨率。 - Raykud
搜索 dp 到像素转换函数,或者最好将所有尺寸放在资源文件中。更多信息请参考:http://developer.android.com/guide/topics/resources/more-resources.html#Dimension - sherpya
我尝试过了,但当我将它缩放到dp时,它仍然看起来很模糊。 我给你举个例子:我在Galaxy Tab 2(10.1,1280x800和160密度)和Galaxy S(4',800x480和240密度)上进行测试。假设例如我想加载一个600x600的png图像,在Galaxy Tab上它看起来完美(显然是本地分辨率),但在Galaxy S上它看起来模糊(因为我使用0.625的比例因子进行缩放)。 - Jhon
1个回答

7

获取正在使用的设备密度,并将该密度乘以您选择的一些基础大小(您实际上希望将其绘制成多大或多小?)

示例:

float objectToDrawHeight = 50; //Specified in plain pixels
float objectToDrawWidth = 50; //Specified in plain pixels

float density = getResources().getDisplayMetrics().density;
objectToDrawHeight *= density;
objectToDrawWidth *= density;

//Draw your object using the new (scaled) height and width
//If you are worried about how the object will look on different aspect ratio devices
//  you can get the screen dimensions and use that ratio as a multiplier
//  just as you did with density

Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
float screenDimensionX = display.getWidth();
float screenDimensionY = display.getHeight();

使用密度和屏幕尺寸可以让您绘制任何东西并保持正确的比例。在使用画布时,请假设所有内容都以像素为单位,并且必须进行dpi转换。


我尝试过了,但是您示例中函数返回的密度(float density = getResources().getDisplayMetrics().density;)为160(在Galaxy Tab 2上)。然后objectToDrawHeight将为50 * 160 = 8000,当我将其缩放到实际的screenDimension时,它看起来又变得很糟糕。 - Jhon
嗯,.density 应该返回 1.0,而 .densityDpi 应该返回你提到的 160。你确定你正在使用 density 而不是 densityDpi 吗? - Shellum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接