我想要做的:使用 NSLayoutManager 布局文本并将其 NSTextContainer 设置为字符串数组中最宽字符串(字形)的宽度。
我的问题是:确定总“字形宽度”的方法似乎不正确,因为当我渲染文本时它会换行。
我做了一个实验,使用 32 个字符串和 Monaco 12 点字体,长度报告为 224.0,但如果长度设置为 234.0,文本只会停止换行。
这段代码演示了我上面所说的内容,并在计算的字形宽度的右侧显示了一条垂直线。
- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[[NSColor whiteColor] drawSwatchInRect: bounds];
[[NSColor blackColor] setStroke];
[[NSBezierPath bezierPathWithRect: bounds] stroke];
NSMutableParagraphStyle *thisParagraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
[thisParagraphStyle setLineBreakMode: NSLineBreakByCharWrapping];
[thisParagraphStyle setAlignment: NSLeftTextAlignment];
NSFont *fontUsed = [NSFont fontWithName: @"Monaco" size: 12];
NSDictionary *glyphAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
fontUsed, NSFontAttributeName,
thisParagraphStyle, NSParagraphStyleAttributeName,
[NSColor blackColor], NSForegroundColorAttributeName,
NULL];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"00112233445566778899001122334455\n00112233445566778899001122334455\n00112233445566778899001122334455\n00112233445566778899001122334455\n"];
[textStorage setAttributes: glyphAttributes range: NSMakeRange(0, [textStorage length])];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSSize textContainerSize;
textContainerSize.width = [@"00112233445566778899001122334455" sizeWithAttributes: glyphAttributes].width;
textContainerSize.height = bounds.size.height;
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize: textContainerSize];
[layoutManager addTextContainer:textContainer];
[textContainer release];
[textStorage addLayoutManager:layoutManager];
[layoutManager release];
NSRange glyphRange = [layoutManager glyphRangeForTextContainer: textContainer];
[layoutManager drawGlyphsForGlyphRange: glyphRange atPoint: NSMakePoint(0.0 , 0.0)];
[textStorage release];
[thisParagraphStyle release];
// Indicate right text boundary from computed width
NSBezierPath *rightTextBoundary = [NSBezierPath bezierPath];
[rightTextBoundary moveToPoint: NSMakePoint(textContainerSize.width, 0.0)];
[rightTextBoundary lineToPoint: NSMakePoint(textContainerSize.width, bounds.size.height-1)];
[rightTextBoundary stroke];
NSLog(@"View width: %f", bounds.size.width);
NSLog(@"Calculated width1: %f", textContainerSize.width);
NSLog(@"Calculated width2: %f\n\n", [@"00112233445566778899001122334455" boundingRectWithSize: NSMakeSize(FLT_MAX, FLT_MAX)
options: NSStringDrawingUsesDeviceMetrics
attributes: glyphAttributes].size.width);
}
- (BOOL) isFlipped {
return YES;
}