CALCULATE TEXT WIDTH IN PIXELS

1
GeorgeZaharia's avatar
GeorgeZaharia
  • 23 Dec, 2018
  • 474 words
  • ~2-3 mins
  • 3,985 visits
  • 0 favourites

Hey guys sorry for being away so much, its just life...

Found a couple of questions around the forum this week one tonight and they were related to how one can calculate the length and width of a character or letter inside the text object and center on screen while having a coin adjacent to its left, normally i use top left corner to display info like ingame currency or scoring... but since this was a interesting new way of centering i grabbed a coffee and chiseled at it.

now normally Construct doesn't have that value information but it gives us the count of the characters and the size of the font and from there we can workout the problem.

in order to solve the problem we have a couple of missing values, such as:

what is the height of the letter and what is the width of a letter in a font family ( for this example we will use Arial as is the most spread out family online and devices.) or we can simply ask what is the font family letter aspect ratio.

and what is 1pt converted to pixels.

if we have all those values we can quickly calculate the total length of the letters in pixels and set the width and height of text object accurately to 0.0000001 decimal, in Construct atleast.

now in order to find out the 1pt value to pixels i cheated a bit and i used a online convertor, and the source i found gave me 1pt=1.333333px

then i kinda cheated again, and looked for the aspect ratio of the font family arial, now that information personally i couldn't find it quickly on wikipedia but i found it on some tech css website that had a list saying a 0.52 aspect ratio for arial family.(now i don't know if they were right or not, but for construct the arial family the aspect ratio of the letters is 0.56 had to gradually increase the value 0.01 by 0.01 till was close to what i wanted to achieve... and it worked, therefor finding the 2nd missing vital information).

the font size we already have it because the object text has a expression called text.facesize, which is the font size for that text object.

with all our x1x2x3 yz values in place we can now calculate the length of the text and accurately center it in the center of the screen.

the example i made was tested on a desktop pc i work on on chrome browser, now it should work on android phones and retina x2 devices, if doesn't work for retina x2 u can use spritefont.

now is a bit of long typing the blog entry, so il keep it short and post the Construct 3 project ^_^ its 3 AM here.

Download center_coin+text Enjoy.

Subscribe

Get emailed when there are new posts!

  • 2 Comments

  • Order by
Want to leave a comment? Login or Register an account!