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

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

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


当前回答

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

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

其他回答

是这样的:

public class ScreenUtils {

    public static float dpToPx(Context context, float dp) {
        if (context == null) {
            return -1;
        }
        return dp * context.getResources().getDisplayMetrics().density;
    }

    public static float pxToDp(Context context, float px) {
        if (context == null) {
            return -1;
        }
        return px / context.getResources().getDisplayMetrics().density;
    }
}

根据上下文,返回浮点值,静态方法

来自:https://github.com/Trinea/android-common/blob/master/src/cn/trinea/android/common/util/ScreenUtils.java课时

Xamarin的。安卓

float DpToPixel(float dp)
{
    var resources = Context.Resources;
    var metrics = resources.DisplayMetrics;
    return dp * ((float)metrics.DensityDpi / (int)DisplayMetricsDensity.Default);
}

当你在制作一个自定义渲染器时,使它是非静态的是必要的

最好的答案来自Android框架本身:只要使用这个等式…

public static int dpToPixels(final DisplayMetrics display_metrics, final float dps) {
    final float scale = display_metrics.density;
    return (int) (dps * scale + 0.5f);
}

(将dp转换为px)

你可以用这个..没有上下文

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

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

正如@Stan提到的…如果系统改变密度,使用这种方法可能会导致问题。所以要注意这一点!

就我个人而言,我使用上下文来做到这一点。这是我想和你分享的另一种方法

上面有很多很棒的解决方案。然而,我发现最好的解决方案是谷歌的设计:

https://design.google.com/devices/