Convert dip to px in Android
Asked Answered
C

4

55

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 in my Activity class

Board board = new Board(this);
board.execute(URL);

This code runs asynchronously. Please help me.

public float getpixels(int dp){
    //Resources r = boardContext.getResources();
    //float px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpis, r.getDisplayMetrics());
        
    final float scale = this.boardContext.getResources().getDisplayMetrics().density;
    int px = (int) (dp * scale + 0.5f);

    return px;
}
Conwell answered 6/12, 2011 at 11:28 Comment(1)
What error do you get? boardContext is null? getResources is null?Uptodate
R
23

The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See Convert dp units to pixel units for more information.

You could try:

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

Hope this helps...

Reset answered 6/12, 2011 at 11:56 Comment(0)
S
139

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)
Sedulous answered 6/12, 2011 at 11:50 Comment(2)
what would you return float for pixel? Shouldn't it be casted to int?Lodie
Works, BUT seems that applying the w, h to my floating activity, android adds 16dp to right and left (total 32dp), there for the dipValue i had to pass is the dipValue i had in the layout xml + 32dp - fixed itAsel
T
44

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

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

It's easier...

Tepee answered 20/10, 2014 at 13:46 Comment(0)
R
23

The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See Convert dp units to pixel units for more information.

You could try:

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

Hope this helps...

Reset answered 6/12, 2011 at 11:56 Comment(0)
A
8

Try this for without passing context:

 public static float dipToPixels(float dipValue) {
     return TypedValue.applyDimension(
         TypedValue.COMPLEX_UNIT_DIP,
         dipValue,
         Resources.getSystem().getDisplayMetrics()
     );
 }
Allele answered 5/3, 2018 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.