Converting dp to px without Context
Asked Answered
L

2

8

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?

Lan answered 8/3, 2017 at 14:9 Comment(0)
W
7

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

Wilhelminawilhelmine answered 8/3, 2017 at 14:25 Comment(1)
Thanks. In my case app doesn't have "cast" option, but it probably can fail on strange devices like this one.Richie
B
1

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()
}
Beauregard answered 28/8, 2021 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.