user961524 user961524 - 1 year ago 100
Android Question

Convert dip to px in Android

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);

This code run 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;


Answer Source

Try this:

public static float dipToPixels(Context context, float dipValue) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download