Best way to measure exact text end position #3006
-
|
I'd like to find out the exact position at which a paragraph of text I'm planning to render to an image will end, given a set of RichTextOptions. I know I can use the TextMeasurer methods to get a rectangular bounding box, but I need to know the X position at which the last line will end so that I can continue drawing stuff at that position. (Specifically, I'm trying to create a system to replace special tokens in text with inline icons, so if there's an easier way to do that please let me know) Looking at what TextMeasurer is doing internally it seems like this information is calculated, I'm just not sure if it's exposed anywhere? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
You would measure the character bounds. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help! I eventually got this working - it's quite convoluted though. Implementation is here for the benefit of any future googlers who may happen to be doing something similar: https://github.com/Autoquark/SpaceWarDiscordApp/blob/main/ImageGeneration/ImageProcessingExtensions.cs (in DrawTextWithInlineIcons) The general idea is that we find tokens representing where inline icons should be inserted (e.g. \$star\$), replace them in the text with a series of non-breaking spaces in order to ensure we get a contiguous blank area big enough to draw the icon, then use TryMeasureCharacterBounds to find out where those spaces are going to be rendered on the image and draw the icon over them. It's complicated by having to fix up text runs and the fact that TryMeasureCharacterBounds omits from the results whitespace that would be at the end of a line, since it isn't actually rendered. |
Beta Was this translation helpful? Give feedback.
You would measure the character bounds.
https://docs.sixlabors.com/api/Fonts/SixLabors.Fonts.TextMeasurer.html#SixLabors_Fonts_TextMeasurer_TryMeasureCharacterBounds_System_ReadOnlySpan_System_Char__SixLabors_Fonts_TextOptions_System_ReadOnlySpan_SixLabors_Fonts_GlyphBounds___