1

I'm designing something that requires very precise spacing, so I need to allocate the correct space for each column.

I have a huge list of names, very long, and I want to calculate how much space the longest name would take up. Having 'iiii' is different than 'mmmm' even though they have the same amount of characters, so that obviously, depending on the font used, should be taken into account.

Kheldar
  • 5,361
  • 3
  • 34
  • 63
  • If you can do without kerning (for finding the longest string), bear in mind that rendering a string to find the width is more expensive than measuring the width of every letter once and adding those values over the string. – Ulrich Schwarz Jan 01 '11 at 15:00
  • possible duplicate of [How to determine the size of a string given a font.](http://stackoverflow.com/questions/721168/how-to-determine-the-size-of-a-string-given-a-font) – Nifle Jan 01 '11 at 15:42
  • Which platform (win32/64, osX, ios android), which language (C#, Java, Delphi)? – Johan Sep 23 '11 at 11:47

2 Answers2

0

If you're on win32, I think GetTextExtent is the API call you're looking for. Other platforms should have similar APIs.

afrazier
  • 4,784
  • 2
  • 27
  • 30
0

Most platforms (and/or font handling libraries) provide a way to obtain the font-wide maximum advance width, which you could use to allocate column width if you absolutely need to fit. This should be a very inexpensive operation as you're simply looking up a value, then multiplying by the number of characters in the string(s), as opposed to actually rendering the strings.

Some platforms also provide a font-wide average advance width value; if you just need to get "pretty close" you could probably devise a formula that takes the average into account.

Under Win32, GetTextMetrics returns a TEXTMETRIC structure which contains both the max and average. As mentioned above, other platforms should have similar APIs but you'll have to figure that out yourself, or edit your question so we can help you.

djangodude
  • 5,362
  • 3
  • 27
  • 39