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

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

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


当前回答

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

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

其他回答

对于使用Kotlin的人:

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

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

用法:

64.toPx
32.toDp

如果在values/dimen中有维度,可能最好的方法是直接从getDimension()方法获取维度,它将返回已经转换为像素值的维度。

context.getResources().getDimension(R.dimen.my_dimension)

为了更好地解释这个,

getDimension(int resourceId) 

将返回已转换为像素AS FLOAT的维度。

getDimensionPixelSize(int resourceId)

将返回相同的,但截断为int,所以AS AN 整数。

参见Android参考

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)

float scaleValue = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scaleValue + 0.5f);