我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。

我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。

有没有什么简单的方法将像素转换为dp? 有什么建议吗?


当前回答

从DP到像素

在dimensions .xml中创建一个值

<dimen name="textSize">20dp</dimen>

以像素为单位获取该值:

int sizeInPixel = context.getResources().getDimensionPixelSize(R.dimen.textSize);

其他回答

PX和DP不同但相似。

DP是当你只考虑屏幕的物理尺寸时的分辨率。当你使用DP时,它会将你的布局缩放到其他类似大小的屏幕,具有不同的像素密度。

有时候你确实需要像素,当你在代码中处理维度时,你总是在处理真实的像素,除非你转换它们。

所以在android设备上,正常尺寸的hdpi屏幕,800x480在DP上是533x320。将DP转换为像素/1.5,转换回*1.5。这只是针对一个屏幕大小和dpi,它会根据设计而改变。我们的美工给我像素,然后我用上面的1.5等式将其转换为DP。

这适用于我(c#):

int pixels = (int)((dp) * Resources.System.DisplayMetrics.Density + 0.5f);

将像素转换为dp使用TypedValue。

正如文档中提到的:动态类型数据值的容器。

并使用applyDimension方法:

public static float applyDimension (int unit, float value, DisplayMetrics metrics) 

将一个保存维度的已解包的复杂数据值转换为其最终浮点值,如下所示:

Resources resource = getResources();
float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 69, resource.getDisplayMetrics());

希望能有所帮助。

如果您想要整数值,则使用Math.round()将浮点数四舍五入为最接近的整数。

public static int pxFromDp(final float dp) {
        return Math.round(dp * Resources.getSystem().getDisplayMetrics().density);
    }

要将dp转换为px,这段代码可能很有用:

public static int dpToPx(Context context, int dp) {
       final float scale = context.getResources().getDisplayMetrics().density;
       return (int) (dp * scale + 0.5f);
    }