views:

153

answers:

1

I want to know the width of an NSString displayed on the screen in pixels. So I can fit an NSTextField its bounds to be exactly the length of the string itself. So I used IB's "Label" NSTextField and for those who don't know what I mean, I got a label with title "Label", font "Lucida Grande 13px", not selectable, not editable, regular size, no background and according to IB its width is 38px wide.

If I want to get its width programatically I use

[@"Label" sizeWithAttributes: [NSDictionary dictionaryWithObject: [NSFont fontWithName: @"Lucida Grande" size: 13] forKey: NSFontAttributeName]].width

Which will give me 33.293457 . So that's about 5 px of the real width..

A: 

That actually sounds reasonable. You are comparing two different widths; the width of a raw string vs. the width of a string contained in an NSTextField. The contained string likely has just a tad bit of padding on either end, among other minor differences.

bbum
Could be, but the height is correct with 6 digits after the comma... After doing some tests it looks like it results in always ~5 px smaller than the original.. That's why I suspect that something's wrong with the attributes and I don't know what. Even passing the correct color, background style, paragraph style, line break mode and direction gives me the same results of ~5 px smaller.