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"
@implementation
View
-
(
id
)
initWithFrame:
(
CGRect
)
frame
{
self
=
[
super
initWithFrame
:
frame
];
if
(
self
)
{
// Initialization code
}
return
self
;
}
-
(
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
=
[
UIFont
fontWithName
:
@"HelveticaNeue-Bold"
size:
40.0f
];
NSString
*
myString
=
@"Some String"
;
[
myString
drawAtPoint
:
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
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.