Cocoa get line width in pixels from font

Hi guys, I am trying to find the width in pixels of a string from a font and font size. I am currently using this code, but it does not work 100% of the time. Is there any other way to do this?

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

NSAttributedString provided by the -size application with add-ons for the application set.

 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; 
+7
source

Here is what I use to get the row size ...

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

NOTE. . If you add a line to the text box, I find that you need to add from 10 to size.width for it.

+2
source

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

+1
source

Here is 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 stringAttributes, which can 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]; 
0
source

All Articles