我目前正在使用NSString-helper方法在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];
}
编辑:我正在尝试优化一个向屏幕输出大量文本序列(如10000个数字序列(的应用程序。每个数字周围都有标记和/或它们之间有不同的空间,有些数字在上面、下面或之间有点和/或线。它类似于本文档第二页顶部的示例,但输出要多得多。
您可以从删除以下行开始:
[path moveToPoint: NSMakePoint(0, 7)];
这样您的路径就不会被绑定到视图中的特定位置。完成后,您可以调用方法来获取路径、移动到一个点、绘制路径、移动至另一个点和绘制路径,依此类推。如果您想从路径描述中的起点移动,请使用-relativeMoveToPoint:
。
看起来这可能会奏效,但我不确定这是否是最好的方法?
// Create the path
NSBezierPath* path = [self bezierPathFromText: @"Fish are fun to watch in a fish tank, but not fun to eat, or something like that." maxWidth: width];
// Draw a copy of it at a transformed (moved) location
NSAffineTransform* transform = [[NSAffineTransform alloc] init];
[transform translateXBy: 10 yBy: 10];
NSBezierPath* path2 = [path copy];
[path2 transformUsingAffineTransform: transform];
[[NSColor greenColor] setFill];
[path2 fill];
[path2 release];
[transform release];
[path2 release];
// Draw another copy of it at a transformed (moved) location
transform = [[NSAffineTransform alloc] init];
[transform translateXBy: 10 yBy: 40];
path2 = [path copy];
[path2 transformUsingAffineTransform: transform];
[[NSColor greenColor] setFill];
[path2 fill];
[path2 release];
[transform release];