How do I calculate text width in pixels

0 favourites
  • 4 posts
From the Asset Store
Vintage steam pixels for your UI! 125 unique assets in a single pack!
  • Oh Hi ! I was trying to get the width of the actual text in the text object

    Like for instance: If i type in text object "HELLO WORLD" based on each character width its will automaticly calculate the entire width of a string in pixels

    for example

    H - 3 pixels

    E - 3 pixels

    L - 2.5 pixels

    ...

    and the entire width = 3 + 3 + 2.5 +2.5 ... pixels

    So is it possible ?

    Can it work with differnt fonts and sizes ?

    Or am i supposed to find the exact measurment of each character in font by myself ?

    sorry if i missed an equal topic on the forum

    i will appreciate any help u would provide

  • That won't work with regular text as those values can vary system to system.

    About all you can measure is textwidth.

    Unless you use Spritefont that is.

  • One way you can do it is by calculating all the letter widths at the start of the game.

    To calculate each letter, you'll have to have a text object with a width of 0, and set the text to a letter. Then have a loop that increases the width by one pixel until the text.textheight value decreases, then use the current width for the width of that letter (store it in an array or dictionary).

    Do this for each letter or character.

    Some notes:

    the textheight is the height of the text, so if one line is 20 pixels high, then two lines of text is 40, etc.. So when you have the width of the text object smaller than a letter width, it will cause it to jump to the second line.. So when you increase the width it eventually as room to place the letter on the first line.

    Also at the beginning, the textheight will be 0, so it will jump to 40, then 20 for example.. You'd stop adjusting the width when that value decreases.

    I think it might pad the letters by a pixel, so you might have to remove 2 or 3 from the found width.. There might be other things to keep in mind too, but this might be a good start point.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Thanks for a such quick reply newt and Prominent ! ill reconsider my project around using Spritefont

    By the way Prominent solution looks really interesting i think it will have it use on a later stages

    Thanks u all

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)