在canvas.drawBitmap中使用dpi而不是像素

时间:2012-08-21 22:23:16

标签: android canvas pixels dpi

我已阅读"屏幕支持API指南"(http://developer.android.com/guide/practices/screens_support.html)以及更多资源,但我无法理解dpi如何的工作原理。

我正在开发游戏,而且我没有使用任何布局(我将使用canvas.drawbitmap等功能自己绘制)。但是当我使用Canvas.Drawbitmap函数时,我需要指定我想要绘制图像的屏幕像素。

所以我现在使用固定分辨率(1280x800)工作,我使用drawable-nodpi文件夹,如果手机的屏幕更宽或更窄,我会稍后调整画布。问题在于,当分辨率不是原生分辨率(1280x800)时,图像看起来很糟糕。

我该怎么做才能解决这个问题?我在3天内阅读和阅读,但所有解释和示例都与Layouts,Nine Patches等有关。

1 个答案:

答案 0 :(得分:6)

获取正在使用的设备的密度,并将该密度乘以您选择的某个基本尺寸(您实际想要绘制多大或多小?)

示例:

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转换。

相关问题