val Int.dpToPx: Int
get() = Math.round(this * Resources.getSystem().displayMetrics.density)
val Int.pxToDp: Int
get() = Math.round(this / Resources.getSystem().displayMetrics.density)
/**
* Converts Pixel to DP.
*/
val Int.pxToDp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
/**
* Converts DP to Pixel.
*/
val Int.dpToPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.dp get() = this / (Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
val Float.dp get() = this / (Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
val Int.px get() = this * Resources.getSystem().displayMetrics.density
val Float.px get() = this * Resources.getSystem().displayMetrics.density
用法:
val dpValue = 2.dp
val pxFromDpValue = 2.px
重要消息:
我不确定 Resources.getSystem()是否能够正确地适应方向的改变。
如果想在例如片段或活动中工作,只需将它添加到基本片段或基本活动中,并像这样使用它:
abstract class BaseFragment : Fragment() {
val Int.dp get() = this / (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
val Float.dp get() = this / (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
val Int.px get() = this * resources.displayMetrics.density
val Float.px get() = this * resources.displayMetrics.density
.......
}