views:

87

answers:

2

Hey guys, I am trying to find the width in pixels of a string from the font and font size. I am currently using this code, but it is not working 100% of the time. Is there another way to do it?

NSSize textSize = [aTextLayer.string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:@"Bank Gothic Medium", NSFontNameAttribute, [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute, nil]];
+1  A: 

NSAttributedString is granted a -size method by the Application Kit Additions.

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
    @"Bank Gothic Medium", NSFontNameAttribute,
    [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute,
    nil];
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:aTextLayer.string attributes:attributes];
NSSize size = attributedString.size;
zneak
That didn't fix it. It's still not changing. The fontSize will change from 10 to 22, but the size is still the same...
+1  A: 

Try using the actual NSFont (or UIFont) object instead of just the name of the font.

Dave DeLong
Documentation says `NSFontNameAttribute` is "An optional `NSString` object that specifies the font name."
zneak
Awesome! Thanks! This is actually going to fix some other problems we had as well!
user445229: Did you accept the answer you didn't mean to?
Peter Hosey