# How do I calculate text width in pixels

Get help using Construct 2

### » Fri Apr 21, 2017 9:31 pm

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
B
37
S
16
G
3
Posts: 10
Reputation: 4,362

### » Fri Apr 21, 2017 10:13 pm

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.
B
175
S
50
G
200
Posts: 8,630
Reputation: 124,536

### » Fri Apr 21, 2017 11:03 pm

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.
B
51
S
24
G
68
Posts: 1,182
Reputation: 40,340

### » Sat Apr 22, 2017 11:05 am

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
B
37
S
16
G
3
Posts: 10
Reputation: 4,362

### Who is online

Users browsing this forum: No registered users and 65 guests