본문 바로가기

Android - Snippet

[Android] PxToDp, DpToPx

인자,리턴 타입은 변경 적용해서 쓰시면 됩니다


fun convertPixelsToDp(px: Int, context: Context): Int {
    val metrics = context.resources.displayMetrics
    return px / (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

fun convertDpToPixelsTo(dp: Float, context: Context): Int {
    val metrics = context.resources.displayMetrics;
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics).toInt()
}