Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

572

CHAPTER 16: Drawing with Quartz and OpenGL

The QuartzFun Application

Our next application is a simple drawing program (see Figure 16–5). We’re going to build this application twice: now using Quartz, and later using OpenGL ES. This will give you a real feel for the difference between the two environments.

Figure 16–5. Our chapter’s simple drawing application in action

The application features a bar across the top and one across the bottom, each with a segmented control. The control at the top lets you change the drawing color, and the one at the bottom lets you change the shape to be drawn. When you touch and drag, the selected shape will be drawn in the selected color. To minimize the application’s complexity, only one shape will be drawn at a time.

Setting Up the QuartzFun Application

In Xcode, create a new iPhone project using the Single View Application template (with ARC but not using storyboards) and call it QuartzFun. The template has already provided us with an application delegate and a view controller. We’re going to be executing our custom drawing in a custom view, so we need to also create a subclass of UIView where we’ll do the drawing by overriding the drawRect: method.

www.it-ebooks.info

CHAPTER 16: Drawing with Quartz and OpenGL

573

With the QuartzFun folder selected (the folder that currently contains the app delegate and view controller files), press N to bring up the new file assistant, and then select Objective-C class from the Cocoa Touch section. Name the new class

BIDQuartzFunView and make it a subclass of UIView.

We’re going to define some constants, as we’ve done in previous projects, but this time, our constants will be needed by more than one class. We’ll create a header file just for the constants.

Select the QuartzFun group again and press N to bring up the new file assistant. Select the Header File template from the C and C++ heading, and name the file

BIDConstants.h.

We have two more files to go. If you look at Figure 16–5, you can see that we offer an option to select a random color. UIColor doesn’t have a method to return a random color, so we’ll need to write code to do that. We could put that code into our controller class, but because we’re savvy Objective-C programmers, we’ll put it into a category on UIColor.

Again, select the QuartzFun folder and press N to bring up the new file assistant. Select the Objective-C category from the Cocoa Touch heading and hit Next. When prompted, name the category BIDRandom and make it a Category on UIColor. Click Next, and save the file into your project folder.

You should now have a new pair of files named UIColor+BIDRandom.h and

UIColor+BIDRandom.m for your category.

Creating a Random Color

Let’s tackle the category first. Add the following line to UIColor+BIDRandom.h:

#import <UIKit/UIKit.h>

@interface UIColor (BIDRandom)

+ (UIColor *)randomColor;

@end

Now, switch over to UIColor+BIDRandom.m, and add this code:

#import "UIColor+BIDRandom.h"

@implementation UIColor (BIDRandom)

+ (UIColor *)randomColor { static BOOL seeded = NO; if (!seeded) {

seeded = YES; srandom(time(NULL));

}

CGFloat red = (CGFloat)random() / (CGFloat)RAND_MAX; CGFloat blue = (CGFloat)random() / (CGFloat)RAND_MAX; CGFloat green = (CGFloat)random() / (CGFloat)RAND_MAX;

return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];

}

@end

www.it-ebooks.info

574

CHAPTER 16: Drawing with Quartz and OpenGL

This is fairly straightforward. We declare a static variable that tells us if this is the first time through the method. The first time this method is called during an application’s run, we will seed the random-number generator. Doing this here means we don’t need to rely on the application doing it somewhere else, and as a result, we can reuse this category in other iOS projects.

Once we’ve made sure the random-number generator is seeded, we generate three random CGFloats with a value between 0.0 and 1.0, and use those three values to create a new color. We set alpha to 1.0 so that all generated colors will be opaque.

Defining Application Constants

Next, we’ll define constants for each of the options that the user can select using the segmented controllers. Single-click BIDConstants.h, and add the following code:

#ifndef QuartzFun_BIDConstants_h #define QuartzFun_BIDConstants_h

typedef enum { kLineShape = 0, kRectShape, kEllipseShape, kImageShape

} ShapeType;

typedef enum { kRedColorTab = 0, kBlueColorTab, kYellowColorTab, kGreenColorTab, kRandomColorTab

} ColorTabIndex;

#define degreesToRadian(x) (M_PI * (x) / 180.0)

#endif

To make our code more readable, we’ve declared two enumeration types using typedef. One will represent the shape options available in our application; the other will represent the various color options available. The values these constants hold will correspond to segments on the two segmented controllers we’ll create in our application.

NOTE: Just in case you haven’t seen this form before, the purpose of the #ifndef compiler directive is to first test if QuartzFun_BIDConstants_h is defined and, if not, to define it. Why not just put in the #define? This way, if a .h file is included more than once, either directly or via other .h files, the directive won’t be duplicated.

www.it-ebooks.info

CHAPTER 16: Drawing with Quartz and OpenGL

575

Implementing the QuartzFunView Skeleton

Since we’re going to do our drawing in a subclass of UIView, let’s set up that class with everything it needs except for the actual code to do the drawing, which we’ll add later. Single-click BIDQuartzFunView.h, and add the following code:

#import <UIKit/UIKit.h>

#import "BIDConstants.h"

@interface BIDQuartzFunView : UIView

@property (nonatomic) CGPoint firstTouch; @property (nonatomic) CGPoint lastTouch;

@property (strong, nonatomic) UIColor *currentColor; @property (nonatomic) ShapeType shapeType;

@property (nonatomic, strong) UIImage *drawImage; @property (nonatomic) BOOL useRandomColor;

@end

First, we import the BIDConstants.h header we just created so we can make use of our enumeration values. We then declare our properties. The first two will track the user’s finger as it drags across the screen. We’ll store the location where the user first touches the screen in firstTouch. We’ll store the location of the user’s finger while dragging and when the drag ends in lastTouch. Our drawing code will use these two variables to determine where to draw the requested shape.

Next, we define a color to hold the user’s color selection and a ShapeType to keep track of the shape the user wants to draw. After that is a UIImage property that will hold the image to be drawn on the screen when the user selects the rightmost toolbar item on the bottom toolbar (see Figure 16–6). The last property is a Boolean that will be used to keep track of whether the user is requesting a random color.

www.it-ebooks.info

576

CHAPTER 16: Drawing with Quartz and OpenGL

Figure 16–6. When drawing a UIImage to the screen, notice that the color control disappears. Can you tell which app is running on the tiny iPhone?

Switch to BIDQuartzFunView.m. We have several changes we need to make in this file. First, we’re going to need access to the randomColor category method we wrote earlier in the chapter, at the top of the file. We’ll also need to synthesize our properties. So add these lines directly below the existing import statement:

#import "UIColor+BIDRandom.h"

and add this one right after the @implementation declaration:

@synthesize firstTouch, lastTouch, currentColor, drawImage, useRandomColor, shapeType;

The template gave us a method called initWithFrame:, but we won’t be using that. Keep in mind that object instances in nibs are stored as archived objects, which is the same mechanism we used in Chapter 13 to archive and load our objects to disk. As a result, when an object instance is loaded from a nib, neither init nor initWithFrame: is ever called. Instead, initWithCoder: is used, so this is where we need to add any initialization code. In our case, we’ll set the initial color value to red, initialize useRandomColor to NO, and load the image file that we’re going to draw later in the chapter. Delete the existing stub implementation of initWithFrame:, and replace it with the following method:

www.it-ebooks.info

CHAPTER 16: Drawing with Quartz and OpenGL

577

-(id)initWithCoder:(NSCoder*)coder {

if (self = [super initWithCoder:coder]) { currentColor = [UIColor redColor]; useRandomColor = NO;

self.drawImage = [UIImage imageNamed:@"iphone.png"] ;

}

return self;

}

After initWithCoder:, we need to add a few more methods to respond to the user’s touches. Insert the following three methods after initWithCoder:.

#pragma mark - Touch Handling

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (useRandomColor) {

self.currentColor = [UIColor randomColor];

}

UITouch *touch = [touches anyObject]; firstTouch = [touch locationInView:self]; lastTouch = [touch locationInView:self]; [self setNeedsDisplay];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject];

lastTouch = [touch locationInView:self];

[self setNeedsDisplay];

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject];

lastTouch = [touch locationInView:self];

[self setNeedsDisplay];

}

These three methods are inherited from UIView (but actually declared in UIView‘s parent UIResponder). They can be overridden to find out where the user is touching the screen. They work as follows:

touchesBegan:withEvent: is called when the user’s finger first touches the screen. In that method, we change the color if the user has selected a random color using the new randomColor method we added to UIColor earlier. After that, we store the current location so that we know where the user first touched the screen, and we indicate that our view needs to be redrawn by calling setNeedsDisplay on self.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]