私がしたいこと: NSLayoutManager を使用してテキストをレイアウトし、その NSTextContainer を文字列の配列で最も広い文字列 (グリフ単位) の幅に設定します。
私の問題は何ですか: テキストをレンダリングすると折り返されるため、「グリフ幅」の合計を決定する方法が正しくないようです。
Monaco 12 ポイント フォントで 32 文字の文字列を使用して実験を行ったところ、長さは 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;
}