20.2. Drawing Text
Problem
You want to be able to draw text on the screen of an iOS device.
Solution
Use the drawAtPoint:withFont: method of NSString.
Discussion
To draw text, we can use some really handy methods built into
the NSString class, such as drawAtPoint:withAttributes:. Before we proceed
further, make sure that you have followed the instructions in this
chapter’s Introduction. You
should now have a view object, subclassed from UIView, named View. Open that file. If the drawRect: instance
method of the view object is commented out, remove the comments until
you have that method in your view object:
#import "View.h"@implementationView-(id)initWithFrame:(CGRect)frame{self=[superinitWithFrame:frame];if(self){// Initialization code}returnself;}-(void)drawRect:(CGRect)rect{}@end
The drawRect: method is where
we’ll do the drawing, as mentioned before. Here we can start loading the
font, and then draw a simple string on the screen at point 40 on the
x-axis and 180 on the y-axis
(Figure 20-6):
-(void)drawRect:(CGRect)rect{UIFont*helveticaBold=[UIFontfontWithName:@"HelveticaNeue-Bold"size:40.0f];NSString*myString=@"Some String";[myStringdrawAtPoint:CGPointMake(40,180)withAttributes:@{NSFontAttributeName:helveticaBold}];}
In this code, we are simply loading a bold Helvetica font at size
40, and using it to draw the text Some
String at point (40, 180).
Figure 20-6. A random string drawn on the graphical context of a view
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access