Thursday, May 7, 2015

Convert dp to px


Convert dp to px


Converting Android’s density independent pixels to actual pixels is quite easy. I always use a function like the below in my projects. It helps keeping apps running correctly with different resolutions:
 
private int dpToPx(int dp) { 

     float density = getApplicationContext().getResources().getDisplayMetrics().density;

     returnMath.round((float)dp* density);

}
For maximum performance, it’s best to fetch the density value once and use it throughout the app life-cycle. Like this:

public class Conv
{
    public static float mDensity;

    public static int dpToPx(int dp)
    {
        return Math.round((float)dp * mDensity);
    }    
}

public class MainActivity extends Activity
{
    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

 Conv.density = getResources().getDisplayMetrics().density;

        Log.i("Test", Integer.toString(Conv.dpToPx(100)));
    }
}


No comments:

Post a Comment