我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
Xamarin的。安卓
float DpToPixel(float dp)
{
var resources = Context.Resources;
var metrics = resources.DisplayMetrics;
return dp * ((float)metrics.DensityDpi / (int)DisplayMetricsDensity.Default);
}
当你在制作一个自定义渲染器时,使它是非静态的是必要的
其他回答
PX和DP不同但相似。
DP是当你只考虑屏幕的物理尺寸时的分辨率。当你使用DP时,它会将你的布局缩放到其他类似大小的屏幕,具有不同的像素密度。
有时候你确实需要像素,当你在代码中处理维度时,你总是在处理真实的像素,除非你转换它们。
所以在android设备上,正常尺寸的hdpi屏幕,800x480在DP上是533x320。将DP转换为像素/1.5,转换回*1.5。这只是针对一个屏幕大小和dpi,它会根据设计而改变。我们的美工给我像素,然后我用上面的1.5等式将其转换为DP。
private fun toDP(context: Context,value: Int): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
value.toFloat(),context.resources.displayMetrics).toInt()
}
对我来说是这样的:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
float d = displaymetrics.density;
int heightInPixels=(int) (h/d);
您可以对宽度执行相同的操作。
更优雅的方法是使用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}")
上面有很多很棒的解决方案。然而,我发现最好的解决方案是谷歌的设计:
https://design.google.com/devices/