我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
更优雅的方法是使用kotlin的扩展函数
/**
* Converts dp to pixel
*/
val Int.dpToPx: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()
/**
* Converts pixel to dp
*/
val Int.pxToDp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()
用法:
println("16 dp in pixel: ${16.dpToPx}")
println("16 px in dp: ${16.pxToDp}")
其他回答
因此,您可以使用以下公式从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);
}
如果您可以使用XML维度,这是非常简单的!
在res/values/ dimensions .xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="thumbnail_height">120dp</dimen>
...
...
</resources>
然后在Java中:
getResources().getDimensionPixelSize(R.dimen.thumbnail_height);
没有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);
}
如果在values/dimen中有维度,可能最好的方法是直接从getDimension()方法获取维度,它将返回已经转换为像素值的维度。
context.getResources().getDimension(R.dimen.my_dimension)
为了更好地解释这个,
getDimension(int resourceId)
将返回已转换为像素AS FLOAT的维度。
getDimensionPixelSize(int resourceId)
将返回相同的,但截断为int,所以AS AN 整数。
参见Android参考
float scaleValue = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scaleValue + 0.5f);