Reputation: 25392
So I made a custom UIView where I can draw lines based on stuff that is happening in the game, and it all seemed to be working properly (each time drawRect: is called, it appends a stroke onto the view)
//Initialization
DrawView* draw = [[DrawView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//And the drawRect method:
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGColorRef r = [self.lineColor CGColor];
CGContextSetStrokeColor(c, CGColorGetComponents(r));
CGContextBeginPath(c);
CGContextMoveToPoint(c, self.start.x, self.start.y);
CGContextAddLineToPoint(c, self.finish.x, self.finish.y);
CGContextStrokePath(c);
}
However, I noticed that I forgot to make the background clear so that it wouldn't block the background of the view. But as soon as I set the background color upon initialization, the drawRect method now resets the context every time drawRect is called.
DrawView* draw = [[DrawView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[draw setBackgroundColor: [UIColor clearColor]];
I want to append the strokes to the context each time drawRect is called, not clear it and then draw, but I also need the background color of the view to be clear.
What am I doing wrong here?
Upvotes: 0
Views: 110
Reputation: 318854
To summarize my comments into an answer:
drawRect:
must redraw everything. It is not designed to simply add one new line each time. Your code doesn't work properly because it is not drawing all lines each time.
You will need to keep track of each line in an array or some other appropriate data structure. Then your drawRect:
method should draw each line each time it is called.
This will allow the background color to work as expected.
This also has the advantage that you can do more with your array of lines. You can provide undo/redo support, scale, rotate, etc.
Another option would be to use UIBezierPath
instead of keeping an array of lines. You can update the path and render it in your drawRect:
method.
And the following lines:
CGColorRef r = [self.lineColor CGColor];
CGContextSetStrokeColor(c, CGColorGetComponents(r));
can be replaced with:
[self.lineColor setStroke];
Upvotes: 1