我目前正在使用 NSString 辅助方法在 NSView 上编写许多文本块......但是在许多情况下编写大量重复文本非常慢。我正在尝试重新编写代码,以便将文本转换为生成一次,然后多次绘制的 NSBezierPath。以下将在屏幕底部绘制文本。
我仍在尝试通读苹果文档以了解其工作原理,但同时我想知道是否有一种简单的方法可以更改此代码以在多个位置重新绘制路径?
// Write a path to the view
NSBezierPath* path = [self bezierPathFromText: @"Hello world!" maxWidth: width];
[[NSColor grayColor] setFill];
[path fill];
这是将一些文本写入路径的方法:
-(NSBezierPath*) bezierPathFromText: (NSString*) text maxWidth: (float) maxWidth {
// Create a container describing the shape of the text area,
// for testing done use the whole width of the NSView.
NSTextContainer* container = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(maxWidth - maxWidth/4, 60)];
// Create a storage object to hold an attributed version of the string to display
NSFont* font = [NSFont fontWithName:@"Helvetica" size: 26];
NSDictionary* attr = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil];
NSTextStorage* storage = [[NSTextStorage alloc] initWithString: text attributes: attr];
// Create a layout manager responsible for writing the text to the NSView
NSLayoutManager* layoutManger = [[NSLayoutManager alloc] init];
[layoutManger addTextContainer: container];
[layoutManger setTextStorage: storage];
NSRange glyphRange = [layoutManger glyphRangeForTextContainer: container];
NSGlyph glyphArray[glyphRange.length];
NSUInteger glyphCount = [layoutManger getGlyphs:glyphArray range:glyphRange];
NSBezierPath* path = [[NSBezierPath alloc] init];
//NSBezierPath *path = [NSBezierPath bezierPathWithRect:NSMakeRect(0, 0, 30, 30)];
[path moveToPoint: NSMakePoint(0, 7)];
[path appendBezierPathWithGlyphs:glyphArray count: glyphCount inFont:font];
// Deallocate unused objects
[layoutManger release];
[storage release];
[container release];
return [path autorelease];
}
编辑:我正在尝试优化输出到屏幕的应用程序,大量文本序列,例如 10,000 个数字的序列。每个数字在其周围都有标记和/或它们之间有不同数量的空间,有些数字在它们的上方、下方或之间有点和/或线。它类似于本文档第二页顶部的示例,但输出要多得多。