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

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

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


当前回答

这适用于我(c#):

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

其他回答

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

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

将像素转换为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());

希望能有所帮助。

因此,您可以使用以下公式从dp中指定的维度计算正确的像素数量

public int convertToPx(int dp) {
    // Get the screen's density scale
    final float scale = getResources().getDisplayMetrics().density;
    // Convert the dps to pixels, based on density scale
    return (int) (dp * scale + 0.5f);
}

使用kotlin-extension会更好

fun Int.toPx(context: Context): Int = (this * context.resources.displayMetrics.density).toInt()

fun Int.toDp(context: Context): Int = (this / context.resources.displayMetrics.density).toInt()

更新:

因为displayMetrics是全局共享资源的一部分,所以我们可以使用Resources. getsystem ()

val Float.toPx get() = this * Resources.getSystem().displayMetrics.density
    
val Float.toDp get() = this / Resources.getSystem().displayMetrics.density
    

    
val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt()
    
val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt()
    

PS:根据@EpicPandaForce的评论:

你不应该为此使用Resources.getSystem(),因为它不处理可折叠文件和Chrome OS设备。

float density = context.getResources().getDisplayMetrics().density;
float px = someDpValue * density;
float dp = somePxValue / density;

密度=

.75在ldpi (120 dpi) 1.0对mdpi (160 dpi;基线) 1.5在hdpi (240 dpi) 2.0 on xhdpi (320 dpi) 3.0 on xxhdpi (480 dpi) 4.0在xxxhdpi (640 dpi)

使用这个在线转换器来处理dpi值。

编辑: dpi桶与密度之间似乎不是1:1的关系。看起来Nexus 5X是xxhdpi的密度值是2.625(而不是3)。你可以在设备指标中自己查看。