Graphics Programs Reference
In-Depth Information
Drawing with TouchDrawView
TouchDrawView will keep track of all of the lines that have been drawn and any that are
currently being drawn. In TouchDrawView.m , create the two collections and import the
header for the Line class.
#import "TouchDrawView.h"
#import "Line.h"
@implementation TouchDrawView
- (id)initWithFrame:(CGRect)r
{
self = [super initWithFrame:r];
if (self) {
linesInProcess = [[NSMutableDictionary alloc] init];
// Don't let the autocomplete fool you on the next line,
// make sure you are instantiating an NSMutableArray
// and not an NSMutableDictionary!
completeLines = [[NSMutableArray alloc] init];
[self setBackgroundColor:[UIColor whiteColor]];
[self setMultipleTouchEnabled:YES];
}
return self;
}
Notice that you explicitly enabled multi-touch events by sending the message setMul-
tipleTouchEnabled: . Without this, only one touch at a time can be active on a view.
If another finger touches the view, it will be ignored, and the view will not be sent
touchesBegan:withEvent: or any of the other UIResponder messages.
Now override the drawRect: method to create lines using functions from Core Graphics:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10.0);
CGContextSetLineCap(context, kCGLineCapRound);
// Draw complete lines in black
[[UIColor blackColor] set];
for (Line *line in completeLines) {
CGContextMoveToPoint(context, [line begin].x, [line begin].y);
CGContextAddLineToPoint(context, [line end].x, [line end].y);
CGContextStrokePath(context);
}
// Draw lines in process in red (Don't copy and paste the previous loop;
// this one is way different)
[[UIColor redColor] set];
for (NSValue *v in linesInProcess) {
Search WWH ::




Custom Search