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

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

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


当前回答

没有Context,优雅的静态方法:

public static int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

public static int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

其他回答

private fun toDP(context: Context,value: Int): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
        value.toFloat(),context.resources.displayMetrics).toInt()
}

因此,您可以使用以下公式从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);
}

这适用于我(c#):

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

你应该像使用像素一样使用dp。他们就是这样;显示独立像素。在中等密度的屏幕上使用相同的数字,在高密度的屏幕上大小将神奇地正确。

然而,听起来你需要的是布局设计中的fill_parent选项。当您希望视图或控件扩展到父容器中的所有剩余大小时,请使用fill_parent。

这应该会给你dp到像素的转换:

public static int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

这应该会给你dp的转换像素:

public static int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}