如何使用Objective-C在自定义视图中绘制文本?

时间:2009-03-03 02:42:08

标签: objective-c cocoa

我已经想出如何使用NSBezierPath类在我的自定义视图类的drawRect函数中绘制形状,但是我似乎无法弄清楚如何绘制文本。以下代码是我到目前为止绘制文本(位于drawRect函数中):

NSText *text = [NSText new];
[text setTextColor: [NSColor yellowColor]];
[text setText: @"Hello!"];

我猜我可能需要提供NSRect或NSPoint来告诉NSText对象在哪里绘制自己,但我在Cocoa文档中找不到有关如何执行此操作的任何内容。

2 个答案:

答案 0 :(得分:23)

你可以尝试这些方法:

//note we are using the convenience method, so we don't need to autorelease the object
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:26], NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName, nil];

NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Cat" attributes: attributes];

NSSize attrSize = [currentText size];
[currentText drawAtPoint:NSMakePoint(yourX, yourY)];

答案 1 :(得分:2)

NSText是一个视图(具体来说,是NSTextView的超类)。

有多种方法可以绘制文本,包括和不包含属性(字体,颜色,段落样式等)。请参阅AppKit's additions to NSStringto NSAttributedString