Skip to content

How do I measure pixel width of a string of text? #105

Answered by wezm
Tameflame asked this question in Q&A
Discussion options

You must be logged in to vote

Unfortunately there is no high-level API that will take an arbitrary Unicode string and return dimensions. You will need to divide up the text by script and perform font matching to determine which font will be used for each run of characters. For a given run of characters in a font and script you would do the following:

  1. Load the font
  2. Shape the text
  3. Perform glyph layout
  4. Obtain the glyph positions
  5. sum up the horizontal advance to calculate the width

https://github.com/yeslogic/allsorts-tools/blob/6ed62c379913fa2c819d52a90c2f4b5efda103ca/src/shape.rs covers steps 1 to 4. Step 5 is something like positions.iter().map(|pos| pos.hori_advance).sum().

glyph_positions returns dimensions in font…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Tameflame
Comment options

Answer selected by Tameflame
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #104 on March 13, 2024 23:40.