Reputation:
I am trying to draw multiple UIBezierPaths on a custom view, with the ability to manipulate them individually.
path and the NSMutableArray to store the paths are instance variables declared like:
@interface MyCustomView : UIView {
UIBezierPath *path;
NSMutableArray *paths; // this is initialized in the init method
}
The path is initialized in touchesBegan as follows:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
path = [[UIBezierPath alloc] init];
[path moveToPoint:[touch locationInView:self];
}
It is moved in the touchesMoved method as follows:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[path addLineToPath:[touch locationInView:self]];
[self setsNeedsDisplay];
}
And I want to store it in the NSMutableArray in touchesEnded:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[path closePath];
[paths addObject:path];
[self setNeedsDisplay];
}
The problem is, after I draw one uibezierpath, and begin to draw one after that, the one i drew first disappears. I'm not sure why this is happening. Thanks in advance!
Note: I know a possible solution is storing all the points of each uibezierpath in a NSMutableArray and redrawing it everytime drawRect is called, but I feel like that is an inefficient implementation.
Upvotes: 0
Views: 787
Reputation: 92306
You didn't show you drawRect:
method, but be aware that in your drawRect:
, you need to draw all paths that you want displayed. Every time drawRect:
is entered, everything you were drawing before is cleared and has to be drawn again, so just drawing the new one will just give the new one and nothing else.
Upvotes: 1
Reputation: 1313
This is happening because you are using a global instance path
. Instead of using a global instance add your path object to mutable array and get wherever you want.
Try replacing your code something like this.
@interface MyCustomView : UIView {
NSMutableArray *paths; // this is initialized in the init method
}
The path is initialized in touchesBegan
as follows:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:[touch locationInView:self];
[paths addObject:path];
}
It is moved in the touchesMoved
method as follows:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UIBezierPath *path = [paths lastObject];
[path addLineToPath:[touch locationInView:self]];
[self setsNeedsDisplay];
}
And I want to store it in the NSMutableArray
in touchesEnded
:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UIBezierPath *path = [paths lastObject];
[path closePath];
[self setNeedsDisplay];
}
Upvotes: 2