iPhone - trying to draw a line on a CALayer
I have a UIView class that I am using to have a CALayer. This layer will be used to draw lines, based on touch.
This is how the class is defined:
- (id)initWithFrame:(C开发者_如何学GoGRect)frame {
self = [super initWithFrame:frame];
if (self == nil) {
return nil;
}
self.layer.backgroundColor = [UIColor redColor].CGColor;
self.userInteractionEnabled = YES;
path = CGPathCreateMutable();
return self;
}
then I have the following lines on touchesBegan, TouchesMoved and touchesEnded...
**touchesBegan**
CGPathMoveToPoint(path, NULL, currentPoint.x, currentPoint.y);
[self.layer setNeedsDisplay];
**touchesMoved**
CGPathAddLineToPoint(path, NULL, currentPoint.x, currentPoint.y);
[self.layer setNeedsDisplay];
**touchesEnded**
CGPathAddLineToPoint(path, NULL, currentPoint.x, currentPoint.y);
[self.layer setNeedsDisplay];
then I have this
-(void)drawInContext:(CGContextRef)context {
CGContextSetStrokeColorWithColor(context, [[UIColor greenColor] CGColor]);
CGContextSetLineWidth(context, 3.0);
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
}
The touchesBegan/Moved/Ended methods are called but this drawInContext method is never called...
what am I missing???
thanks.
You are conflating layers and views and using CG api when you could easily use UIKit api's.
in your init method do this;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self == nil) {
return nil;
}
self.backgroundColor = [UIColor redColor];
// YES is the default for UIView, only UIImageView defaults to NO
//self.userInteractionEnabled = YES;
[self setPath:[UIBezierPath bezierPath]];
[[self path] setLineWidth:3.0];
return self;
}
In your event processing code;
**touchesBegan**
[[self path] moveToPoint:currentPoint];
[self setNeedsDisplay];
**touchesMoved**
[[self path] addLineToPoint:currentPoint];
[self setNeedsDisplay];
**touchesEnded**
[[self path] addLineToPoint:currentPoint];
[self setNeedsDisplay];
Then implement drawRect:
like this;
- (void)drawRect:(CGRect)rect {
[[UIColor greenColor] setStroke];
[[self path] stroke];
}
I typed this in from memory, so it might not compile, it might reformat your harddrive or call invaders from mars to invade your home. Well maybe not that...
The view is the layer's delegate so what you have would have worked if you named your drawing method drawLayer:inContext:
. But don't do it that way, do what I showed above. For the most part you should not have to think about layers.
精彩评论