When using [NSString boundingRectWithSize:options:attributes]
the size of the rect that is returned is taller than I would expect for certain strings. The height returned appears to represent the maximum possible height of a string with the given attributes, rather than the height of the string itself.
Assuming the same attributes and options, the height returned for the string "cars
" is the same height returned for the string "ÉTAS-UNIS
" (note the accent on the E).
I would have expected boundingRectWithSize
to only consider the characters in the given string, which in my opinion would have it return a shorter height for the string "cars
".
In the attached screenshots, I've filled the rect returned from boundingRectWithSize
and outlined in red what I would have assumed the bounding rect should have been. The width of the rect is pretty much as I would expect but the height is considerably taller than I would have expected. Why is that?
Sample code:
NSRect boundingRect = NSZeroRect;
NSSize constraintSize = NSMakeSize(CGFLOAT_MAX, 0);
NSString *lowercaseString = @"cars";
NSString *uppercaseString = @"ÉTAS-UNIS";
NSString *capitalizedString = @"Japan";
NSFont *drawingFont = [NSFont fontWithName:@"Georgia" size:24.0];
NSDictionary *attributes = @{NSFontAttributeName : drawingFont, NSForegroundColorAttributeName : [NSColor blackColor]};
boundingRect = [lowercaseString boundingRectWithSize:constraintSize options:0 attributes:attributes];
NSLog(@"Lowercase rect: %@", NSStringFromRect(boundingRect));
boundingRect = [uppercaseString boundingRectWithSize:constraintSize options:0 attributes:attributes];
NSLog(@"Uppercase rect: %@", NSStringFromRect(boundingRect));
boundingRect = [capitalizedString boundingRectWithSize:constraintSize options:0 attributes:attributes];
NSLog(@"Capitalized rect: %@", NSStringFromRect(boundingRect));
Output:
Lowercase rect: {{0, -6}, {43.1953125, 33}}
Uppercase rect: {{0, -6}, {128.44921875, 33}}
Capitalized rect: {{0, -6}, {64.5, 33}}