我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
如果在values/dimen中有维度,可能最好的方法是直接从getDimension()方法获取维度,它将返回已经转换为像素值的维度。
context.getResources().getDimension(R.dimen.my_dimension)
为了更好地解释这个,
getDimension(int resourceId)
将返回已转换为像素AS FLOAT的维度。
getDimensionPixelSize(int resourceId)
将返回相同的,但截断为int,所以AS AN 整数。
参见Android参考
其他回答
根据Android开发指南:
px = dp * (dpi / 160)
但通常当你收到以像素表示的设计时,你会希望以另一种方式执行这个操作。所以:
dp = px / (dpi / 160)
如果你在一个240dpi的设备上,这个比例是1.5(如前所述),所以这意味着一个60px的图标在应用程序中等于40dp。
科特林:
fun spToPx(ctx: Context, sp: Float): Float {
return sp * ctx.resources.displayMetrics.scaledDensity
}
fun pxToDp(context: Context, px: Float): Float {
return px / context.resources.displayMetrics.density
}
fun dpToPx(context: Context, dp: Float): Float {
return dp * context.resources.displayMetrics.density
}
Java:
public static float spToPx(Context ctx,float sp){
return sp * ctx.getResources().getDisplayMetrics().scaledDensity;
}
public static float pxToDp(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
public static float dpToPx(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
上面有很多很棒的解决方案。然而,我发现最好的解决方案是谷歌的设计:
https://design.google.com/devices/
从DP到像素
在dimensions .xml中创建一个值
<dimen name="textSize">20dp</dimen>
以像素为单位获取该值:
int sizeInPixel = context.getResources().getDimensionPixelSize(R.dimen.textSize);
对我来说是这样的:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
float d = displaymetrics.density;
int heightInPixels=(int) (h/d);
您可以对宽度执行相同的操作。