Mark
03/08/2025, 2:20 PMDensity
as the receiver, but isn’t the API usage cleaner when doing this?
fun TextUnit.scale(scale: Float, density: Density): TextUnit {
if (this.isUnspecified) return this
return with(density) {
(scale * this@scale.toPx()).toSp()
}
}
ephemient
03/08/2025, 3:49 PMDensity
is some outer this
scope, which means you'd have to explicitly qualify this@Layout
in order to use it with that functionZach Klippenstein (he/him) [MOD]
03/08/2025, 4:14 PMMark
03/09/2025, 1:24 AMcontext(Density)
fun TextUnit.scale(scale: Float): TextUnit {
if (this.isUnspecified) return this
return (scale * this@scale.toPx()).toSp()
}
Are context parameters supported by kotlin 2.0.21?
@ephemient my app might be a little odd, but in all the places I call this function, the density is only retrieved/passed for this call, so I pass it by name (e.g. density
). However, it does seem more consistent to use the context receiver/parameter so that scale
is called in the same way as toSp()
etc.CLOVIS
03/09/2025, 12:45 PMephemient
03/13/2025, 3:04 PM.toPx().toSp()
?
fun TextUnit.scale(scale: Float): TextUnit = this * scale
(or don't even have the function at all, just use *
or .times()
)ephemient
03/13/2025, 3:09 PMMark
03/15/2025, 1:39 PMAvoid hardcoding equations using Configuration.fontScale or DisplayMetrics.scaledDensity. Because font scaling is nonlinear, the scaledDensity field is no longer accurate. The fontScale field should be used for informational purposes only because fonts are no longer scaled with a single scalar value.
For example, if the device font size is set to be the max level, then a large font size will not be much larger (rendered size) than a font size with half the value. So if some text measures as 200px and you want to fit it into 100px, then halving the font size will not work (unless the device is set to use default font scaling). It’s a super-easy mistake to make when manipulating font sizes in order to fit text.