Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android compose has textSize unit em

Android compose has textSize unit em, but no dp. What is "em"? What's difference between em, sp and dp and why no dp? How convert to em from other units?

Text(text = "Hello",fontSize = 5.em)
like image 398
Александр Щербаков Avatar asked Apr 29 '26 18:04

Александр Щербаков


1 Answers

The terms:

  • dp - density independent pixels - this is a pixel value that is automatically scaled for you based on the density of a device
  • sp - scalable pixels - like dp but also scaled based on a user's text preferences (e.g., accessibility settings to increase the font size)
  • em - relative value compared to the point size (e.g., if you had a 12 point font, 12 points would be 1em)

Jetpack Compose takes the more protective approach of not letting you specify font sizes in dp. That's because if you did something like 10.dp, a user who relies on larger text sizes will not be able to read the text no matter how large they put their preferences in the system settings.

Text sizes in Jetpack Compose are passed via a TextUnit. When you do something like fontSize = 1.1em, you're triggering an extension method that makes a TextUnit for you but it doesn't have any pixel size. The size isn't known until there's a TextStyle, which specifies the required font attributes.

Asking how many dp or sp a given em value is could be equated to asking something like how big is 50%? The next question is 50% of what?

like image 158
Ian G. Clifton Avatar answered May 01 '26 08:05

Ian G. Clifton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!