Jetpack Compose: 为什么LocalConfiguration.current.screenWidthDp是整数而不是浮点数?

huangapple go评论55阅读模式
英文:

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

问题

LocalConfiguration.current.screenWidthDp 作为整数(Int)似乎会导致从 dp 到像素的转换不够准确。

例如,对于一个像素密度为 420,宽度为 1080 像素的设备,以 dp 为单位的宽度 = 1080 * 160/420 = 411.4285714。

然而,如果你使用 411 或 412 的整数来从 dp 转换为像素,那么像素将分别是 1078.875 或 1081.5。无法简单四舍五入得到 1080 这个数字。

大多数用例是否更喜欢 LocalConfiguration.current.screenWidthDp 是整数(Int)呢?

英文:

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

得分: 0

LocalConfiguration.current 是一个CompositionLocal,它公开了平台的 Configuration。简单来说,你可以把它看作是一个参数,会自动传递给你的每个组合件,运行时会知道它以便在更改时重新组合。从这个意义上讲,这个值是一个整数,因为它表示 Configuration 的 screenWidthDp 整数值。

之所以在平台级别表示为整数,是因为它始终是正整数值,因为这是用于确定给定配置中使用的正确资源的值。换句话说,资源限定符处理整数值,因此配置公开整数值。

如果你想要做类似绘制组件的整个宽度的线的事情,你可以一直使用像素。对于这种情况,与实际线条的物理大小无关,因此密度独立像素对这种情况并不重要。与需要大致手指大小或更大(~48dp+)的按钮之类的情况相比,这是不同的。

在你关心物理大小的情况下,你可以从 dp 开始,当需要进行实际绘制时再转换为像素(通常只需使用类似 16.dp.toPx() 的东西)。

英文:

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

huangapple
  • 本文由 发表于 2023年2月14日 04:35:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定