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)

Upvotes: 10

Views: 4940

Answers (2)

Ian G. Clifton
Ian G. Clifton

Reputation: 9449

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?

Upvotes: 5

Vidyesh Churi
Vidyesh Churi

Reputation: 2589

In fontSize, EM or em stands for "Relative font size". 1.em = 100% So in your case

Text(text = "Hello",fontSize = 5.em)

is 500% of normal text size i.e. original size x 5.

Similarly, SP or sp stands for "Scaled pixels" so you can write

Text(text = "Hello",fontSize = 30.sp)

Upvotes: 3

Related Questions