boundingRectWithSize返回不必要的高度

boundingRectWithSize返回不必要的高度

本文介绍了NSString boundingRectWithSize返回不必要的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 [NSString boundingRectWithSize:options:attributes] 时,返回的rect的大小比我对某些字符串所期望的大。返回的高度似乎表示具有给定属性的字符串的最大可能高度,而不是字符串本身的高度。

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.

假设相同的属性和选项,字符串 cars 返回的高度是返回的字符串ÉTAS-UNIS (注意E上的重音)。

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).

我本来希望 boundingRectWithSize 只考虑给定字符串中的字符,为字符串 cars 返回较短的高度。

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".

在附加的屏幕截图中,我填写了 boundingRectWithSize 返回的rect,假设边界矩形应该已经。矩形的宽度是我所期望的,但是高度比我预期的高得多。这是为什么?

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?

示例代码:

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

输出:

Lowercase rect: {{0, -6}, {43.1953125, 33}}
Uppercase rect: {{0, -6}, {128.44921875, 33}}
Capitalized rect: {{0, -6}, {64.5, 33}}


推荐答案

您可能想在选项中使用 NSStringDrawingUsesDeviceMetrics 。从:

You might want to use NSStringDrawingUsesDeviceMetrics in the options. From the docs:

在计算布局时使用图像字形边界(而不是印刷边界)。

Use the image glyph bounds (instead of the typographic bounds) when computing layout.

这篇关于NSString boundingRectWithSize返回不必要的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:36