我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
对我来说是这样的:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
float d = displaymetrics.density;
int heightInPixels=(int) (h/d);
您可以对宽度执行相同的操作。
其他回答
将dp转换为像素
public static int dp2px(Resources resource, int dp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,resource.getDisplayMetrics()
);
}
将像素转换为dp。
public static float px2dp(Resources resource, float px) {
return (float)TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PX,
px,
resource.getDisplayMetrics()
);
}
其中resource为context.getResources()。
根据Android开发指南:
px = dp * (dpi / 160)
但通常当你收到以像素表示的设计时,你会希望以另一种方式执行这个操作。所以:
dp = px / (dpi / 160)
如果你在一个240dpi的设备上,这个比例是1.5(如前所述),所以这意味着一个60px的图标在应用程序中等于40dp。
PX和DP不同但相似。
DP是当你只考虑屏幕的物理尺寸时的分辨率。当你使用DP时,它会将你的布局缩放到其他类似大小的屏幕,具有不同的像素密度。
有时候你确实需要像素,当你在代码中处理维度时,你总是在处理真实的像素,除非你转换它们。
所以在android设备上,正常尺寸的hdpi屏幕,800x480在DP上是533x320。将DP转换为像素/1.5,转换回*1.5。这只是针对一个屏幕大小和dpi,它会根据设计而改变。我们的美工给我像素,然后我用上面的1.5等式将其转换为DP。
最好的答案来自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)
使用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设备。