프로그래밍/Android

[Java/Kotlin] 안드로이드 DP to PX 변환하기

Lou Park 2021. 1. 8. 23:17

DP to PX, 자매품 SP to PX 까지!

public static int convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return (int) px;
}

public static int convertSpToPx(float sp, Context context) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
}