Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting dp to px without Context

There is a very neat way of converting dp to px without Context, and it goes like this:

public static int dpToPx(int dp) {
    float density = Resources.getSystem().getDisplayMetrics().density;
    return Math.round((float) dp * density);
}

In every Google's example on Google GitHub page they are using the following approach:

public static int convertDpToPixel(Context ctx, int dp) {
    float density = ctx.getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
}

So is there something wrong with the first approach? For me it works fine in all my apps, but I want to know is there some case where it might fail?

like image 435
Vladimir Jovanović Avatar asked Mar 08 '17 14:03

Vladimir Jovanović


People also ask

What is the best way to convert DP to pixel?

The best way to convert dp to px is using the online converter available above because it is accurate and fast. This is a table for some results of conversion dp to px at 320 dpi. you can get more results by using the above dp to pixel converter.

What is DPDP/PX converter?

DP/PX Converter Calculate pixels (and other units) in DPs This tool helps you convert pixels to and from DPs (density independent pixels). Enter a value and unit to calculate the dimensions for the various DPI bins (ldpi, mdpi, hdpi, xhdpi, xxhdpi and xxxhdpi).

Why does the DP/PX converter behave differently when selecting a bin?

The DP/PX converter above behaves slightly different when selecting this bin, as it treats the specified pixel dimension as DP. If you want to know exactly how many dips you own phone has, and much, much more, get our app Introspect from the Play Store.

What is a DP in Android?

Convert px to dp perfectly! DP (A device-independent pixel or density-independent pixel) is a virtual unit recommended for creating the user interface layout in Android systems. This unit expresses dimensions and position in a manner independent of the pixel density ( dpi ).


2 Answers

is there some case where it might fail?

Yes, there is!

Android supports different screens, for example you might cast the app with Chromecast or connect to a different screen by other means. In that case the values will not be converted properly to that other screen.

From the documentation for Resources.getSystem():

Return a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).

like image 163
Eyal Biran Avatar answered Oct 20 '22 02:10

Eyal Biran


Here is a little Kotlin extension function for that:

private fun Context.dpToPx(dp: Float): Float {
    val density = this.resources.displayMetrics.density
    return (dp * density).roundToInt().toFloat()
}
like image 40
Mori Avatar answered Oct 20 '22 03:10

Mori