Convert dip to px in Android

后端 未结 4 1480
忘了有多久
忘了有多久 2020-12-01 03:42

I had written method to get the pixels from dip but it is not working. It give me runtime error.

Actually I was running this method in separate class and initialized

4条回答
  •  难免孤独
    2020-12-01 04:12

    Try this:

    Java

    public static float dipToPixels(Context context, float dipValue) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
    }
    

    Kotlin

    fun Context.dipToPixels(dipValue: Float) =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, resources.displayMetrics)
    

提交回复
热议问题