O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required