Dear experts,
I am trying to have my program determine the character width of the
current (monospaced) font, but am having troubles. As a test case, when
I try:
[[NSFont fontWithName:@"Courier" size:14] advancementForGlyph:'a'];
it returns 8.40136718
but that turns out to be not quite right.
I know, because the overall goal is to make the window hold exactly 100
characters in width (but is not quite that when I multiply it out).
On the other hand, if I try:
[[ NSFont fontWithName:@"Courier" size:14 ] boundingRectForGlyph:'a']
which I thought would give me the same number, I actually get something
completely wrong ( a width of 6.61035156), and in fact, different
depending on what glyph is passed to boundingRectForGlyph.
Anybody know what I'm doing wrong here?
thanks
Michael Ash - 27 Nov 2005 12:39 GMT
> Dear experts,
> I am trying to have my program determine the character width of the
[quoted text clipped - 19 lines]
>
> Anybody know what I'm doing wrong here?
Are you sure that the NSGlyph for a lowercase A is really 97? NSGlyph
codes and ASCII character codes are not necessarily related. NSGlyph codes
are essentially arbitrary, so if you're assuming that 'a' gets you the
NSGlyph for a lowercase A, this is most likely your problem.
As far as I know, the only reliable way to go from a character (or string)
to a glyph (or collection of glyphs) is to use NSLayoutManager. And as
long as you're doing that, you can simply ask NSLayoutManager for your
bounding boxes, instead of going back to the original NSFont.

Signature
Michael Ash
Rogue Amoeba Software
None - 28 Nov 2005 00:04 GMT
Well, true, I did not check to see what glyph actually corresponds to
'a', but I figured it shouldn't matter, since it is a monospaced font
(Courier).
> > Dear experts,
> > I am trying to have my program determine the character width of the
[quoted text clipped - 29 lines]
> long as you're doing that, you can simply ask NSLayoutManager for your
> bounding boxes, instead of going back to the original NSFont.
Reinder Verlinde - 27 Nov 2005 13:07 GMT
> I try:
>
> [[NSFont fontWithName:@"Courier" size:14] advancementForGlyph:'a'];
>
> it returns 8.40136718
You probably should use [NSFont maximumAdvancement] here.
> On the other hand, if I try:
>
[quoted text clipped - 3 lines]
> completely wrong ( a width of 6.61035156), and in fact, different
> depending on what glyph is passed to boundingRectForGlyph.
1) That makes sense to me. The bounding rectangle for a glyph is the
smallest rectangle that can cover the entire glyph. That rectangle is
wider for e.g. a 'w' than for an 'i'.
See
<http://developer.apple.com/documentation/Cocoa/Conceptual/FontHandling/T
asks/GettingFontMetrics.html>
2) I do not think that you can be sure that the above returns the width
for the 'a' character. A glyph is not a character. A NSLayoutManager can
convert from characters to glyphs, AFAIK using some non-public API.
Reinder