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

时间:2022-09-07 11:12:44

I've figured out how to use the NSBezierPath class to draw shapes in the drawRect function of my custom view class, however I can't seem to figure out how to draw text. The following code is what I have so far for drawing the text (located in the drawRect function):

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

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

I'm guessing that I may need to supply an NSRect or NSPoint to tell the NSText object where to draw itself, but I can't find anything in the Cocoa documentation about how to do this.

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

2 个解决方案

#1


22  

You could try something along these lines:

你可以尝试这些方面的东西:

//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)];

#2


2  

NSText is a view (specifically, the superclass of NSTextView).

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

There are several ways to draw text, with and without attributes (fonts, colors, paragraph styles, etc.). See AppKit's additions to NSString and to NSAttributedString.

有几种绘制文本的方法,有和没有属性(字体,颜色,段落样式等)。请参阅AppKit对NSString和NSAttributedString的补充。

#1


22  

You could try something along these lines:

你可以尝试这些方面的东西:

//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)];

#2


2  

NSText is a view (specifically, the superclass of NSTextView).

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

There are several ways to draw text, with and without attributes (fonts, colors, paragraph styles, etc.). See AppKit's additions to NSString and to NSAttributedString.

有几种绘制文本的方法,有和没有属性(字体,颜色,段落样式等)。请参阅AppKit对NSString和NSAttributedString的补充。