Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you draw text in a custom view using Objective-C?

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):

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.

like image 326
Jason Roberts Avatar asked Mar 03 '09 02:03

Jason Roberts


2 Answers

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)];
like image 192
Ben Clark-Robinson Avatar answered Sep 18 '22 15:09

Ben Clark-Robinson


NSText is a view (specifically, the superclass of 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.

like image 22
Peter Hosey Avatar answered Sep 17 '22 15:09

Peter Hosey