当使用[NSString boundingRectWithSize:options:attributes]
时,返回的矩形的大小比我期望的某些字符串的大小要高。返回的高度似乎表示具有给定属性的字符串的最大可能高度,而不是字符串本身的高度。
假设属性和选项相同,字符串"cars
“返回的高度与字符串"ÉTAS-UNIS
”返回的高度相同(请注意E上的重音符号)。
我原本期望boundingRectWithSize
只考虑给定字符串中的字符,在我看来,这将使它为字符串"cars
“返回一个较短的高度。
在附加的截图中,我填充了从boundingRectWithSize
返回的矩形,并用红色勾勒出了我认为的边界矩形应该是什么。矩形的宽度和我预期的差不多,但高度比我预期的要高得多。为什么会这样呢?
示例代码:
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}}
发布于 2014-02-05 05:42:48
@omz仍然因为我的工作而获得赞誉。他的回答让我更多地看了看CoreText,因为我假设像boundingRectWithSize
这样的东西最终会调用CoreText函数。
在WWDC2012的第226节中,有一整节专门用于计算线路的指标,令我惊讶的是,他们谈到了一个名为CTLineGetBoundsWithOptions
的新CoreText函数。
据我所知,该方法只记录在CTLine.h
和CoreText Changes
文档中。在文档中进行常规搜索时,(对我来说)肯定不会出现这个问题。
但它似乎可以工作,在我的测试中,对于我系统上安装的所有字体,它返回的结果与boundingRectWithSize
完全相同。更好的是,它似乎比boundingRectWithSize
快近2倍。
正如WWDC视频提到的,为什么你需要计算一个字符串的边界而不考虑像行高这样的东西,这有点令人费解,但如果你确实需要这样做,那么我认为这可能是最好的方法。和往常一样,YMMV。
粗略的示例代码:
NSFont *font = [NSFont systemFontOfSize:13.0];
NSDictionary *attributes = @{(__bridge NSString *)kCTFontAttributeName : font};
NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:self.text attributes:attributes];
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributeString);
CGRect bounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds);
CFRelease(line);
return NSRectFromCGRect(bounds);
发布于 2015-12-10 22:24:37
我尝试了boundingRectWithSize
函数,但它对我不起作用。
起作用的是sizeThatFits
用法:
CGSize maxSize = CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)
CGSize size = [myLabel sizeThatFits:maxSize];
发布于 2019-04-05 03:00:23
基于omz's answer的Swift 3+解决方案
let string: NSString = "test"
let maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
let boundingRect = string.boundingRect(with: maxSize, options: .usesDeviceMetrics, attributes: <string attributes>)
https://stackoverflow.com/questions/21271935
复制相似问题