Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa get string width in pixels from font

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]];
like image 479
user445229 Avatar asked Dec 10 '22 14:12

user445229


2 Answers

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;
like image 191
zneak Avatar answered Jan 01 '23 10:01

zneak


Here is what i use to get the size of a string...

NSSize size = [@"Some text" sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:@"Helvetica Neue Bold" size:24.0f] forKey:NSFontAttributeName]];

NOTE: If you are adding the string to a textfield, i have found that you need to add about 10 to size.width for it to fit.

like image 25
AlBeebe Avatar answered Jan 01 '23 09:01

AlBeebe