user445229
user445229

Reputation: 43

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]];

Upvotes: 4

Views: 5178

Answers (4)

RoyGal
RoyGal

Reputation: 186

Here is yet another example:

NSString *test = [[NSString alloc] initWithFormat:@"%u:%u:%u.000", hours, minutes, seconds];
NSSize boundingSize = {100,300};  //I suppose this is the constraints?
NSRect boundingRect = [test boundingRectWithSize:boundingSize options:NULL attributes:stringAttributes];
point.x -= boundingRect.size.width; //This point points at the end of screen
[test drawAtPoint:point withAttributes:stringAttributes];

Here is for the stringAttributes, that may help noobs like me:

NSMutableDictionary *stringAttributes;
    stringAttributes = [NSMutableDictionary dictionary];
    [stringAttributes setObject:[NSFont fontWithName:@"Monaco" size:16] forKey:NSFontAttributeName];
    [stringAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
    [stringAttributes setObject:[NSColor blackColor] forKey:NSBackgroundColorAttributeName];

Upvotes: 0

AlBeebe
AlBeebe

Reputation: 8121

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.

Upvotes: 4

Dave DeLong
Dave DeLong

Reputation: 243156

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

Upvotes: 1

zneak
zneak

Reputation: 138061

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;

Upvotes: 9

Related Questions