It depends on what font you are using, for example, Courier New is designed to make each character the same width, so if you examine what width is for a character, you can use the get length function for the string (giving you length in characters) and from there calculate its width in pixels. If its width exceeds 511px, you adjust the size accordingly.
If you use a different font, such as Arial, you can do the same, and if you really want it to be accurate, you can group the alphabet into narrow letters, for example, "i", "l", etc., and middle letters like 't' and thick letters like 'o' and capitals. Then you get the number of narrow, medium and thick letters and calculate the size of this data, but personally it is too much for me.
Hope this was helpful.
Edit: Ignore this, I just read about the measurement function. This is a lot less effort than my suggestion.
ChP
source share