so I have a little experience with objective-c, but not a ton. I’m trying to render UIBezierPath via TouchEvents (in other words draw a line with your finger). In addition, I would like to save all the bezierPaths into a NSMutableArray (paths) so that I can move or modify them later. This is the very simplest of applications. My header looks like this:
@interface ViewController : UIViewController{
UIBezierPath* path;
NSMutableArray* paths;
int curThickness;
}
@property (strong, nonatomic) IBOutlet UIView *scene;
@end
Scene is the view which takes up the entire screen and is where I am trying to draw my paths.
Relavent implementation looks like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
NSLog(@"Starting Path");
path = [UIBezierPath bezierPath];
path.lineWidth = 15.0f;
path.lineCapStyle = kCGLineCapRound;
path.lineJoinStyle = kCGLineJoinRound;
path.flatness = 2.0;
path.miterLimit = 4.0;
[path moveToPoint:[touch locationInView:scene]];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
[path addLineToPoint:[touch locationInView:scene]];
[scene setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
NSLog(@"I'm supposed to be drawing something...");
[[UIColor redColor] set];
[path stroke];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"No more touchy feelies");
UITouch *touch = [touches anyObject];
[path addLineToPoint:[touch locationInView:scene]];
[paths addObject:path];
[scene setNeedsDisplay];
NSLog(@"number of paths: %i.", paths.count);
}
When I run it on the emulator, all the events are registered, DrawRect is never called, nothing is drawn on the screen (even if I add a [path trace] at the end of touchesEnded), path is nonEmpty, and paths.count remains zero no matter how many paths I trace.
What am I missing? As always your help is always greatly appreciated.
Couple things that should help you:
UIViewControllerdoes not implement- (void)drawRect.. you need to be doing this code in aUIViewsubclass instead!If your
pathscollection is always zero count, a common mistake causing this is whenpathsitself is nil. (Obj-c doesn’t care if you try to send messages to a nil object, it will just return a default value instead of crashing.) Double-check that you instantiated anNSMutableArrayobject and pointedpathsto it.