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

Jho*_*hon 3 android canvas dpi pixels

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

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

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

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

She*_*lum 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();
Run Code Online (Sandbox Code Playgroud)

使用密度和可能的屏幕尺寸应该允许您绘制任何东西并保持正确缩放.使用画布时,假设所有内容都以像素为单位,并且您必须进行dpi转换.