开发者

Cocoa get string width in pixels from font

开发者 https://www.devze.com 2023-01-15 23:59 出处:网络
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?

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 numb开发者_开发技巧erWithFloat:aTextLayer.fontSize], NSFontSizeAttribute, nil]];


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;


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消