Jetpack Compose: Why is LocalConfiguration.current.screenWidthDp an Int and not a Float?

974 Views Asked by At

It seems having LocalConfiguration.current.screenWidthDp be an Int makes conversions from dp to pixels less accurate.

For example, for a device with density 420 and width in pixels of 1080, the width in dp = 1080 * 160/420 = 411.4285714.

However, if you calculate from dp to pixels using an Int of 411 or 412, then the pixels are 1078.875 or 1081.5. You can't do a simple round to get 1080 from these numbers.

Do most use cases prefer that LocalConfiguration.current.screenWidthDp be an Int?

1

There are 1 best solutions below

1
On BEST ANSWER

LocalConfiguration.current is a CompositionLocal that exposes the platform's Configuration. In simple terms, you can think of it as an parameter that's automatically passed to each of your composables, which the runtime knows about in order to recompose when it changes. In that sense, this value is an int because it represents the Configuration's screenWidthDp int value.

The reason it's represented as an int at the platform level is because it will always be a positive integer value since that's what's used for determining the right resources to use in a given configuration. In other words, resource qualifiers deal with integer values, so the configuration exposes integer values.

If you're looking to do something like drawing a line the full width of a component, you'd work in pixels the whole time. Density independent pixels don't really make sense for that case because you don't care about the physical size of the line. Compare that to the case of something like a button where the physical size does matter since it needs to be roughly finger size or larger (~48dp+).

In cases where you do care about the physical size, you'd start with dp and convert to pixels when you need to do the actual drawing (typically just using something like 16.dp.toPx())