Convert dip to px in Android

后端 未结 4 1458
忘了有多久
忘了有多久 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 03:52

    You can add the dp value in dimen.xml and use

    int pixels = getResources().getDimensionPixelSize(R.dimen.idDimension);
    

    It's easier...

    0 讨论(0)
  • 2020-12-01 04:02

    Try this : For without passing context

     public static float dipToPixels(float dipValue) {
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, Resources.getSystem().getDisplayMetrics());
        }
    
    0 讨论(0)
  • 2020-12-01 04:04

    The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See http://developer.android.com/guide/practices/screens_support.html for more information.

    You could try:

    public static int convertDipToPixels(float dips)
    {
        return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f);
    }
    

    Hope this helps...

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题