I've subclassed a UIView and overridden the touchesBegan, touchesMoved, touchesEnded, and drawRect methods to create an app that allows the user to draw by touching the screen. I'm using the Quartz 2D library to do the drawings.
In touchesBegan, touchesMoved, and touchesEnded, I keep track of the current and previous locations of the touch event. Each time the touch moves and when the touch ends, I call setNeedsDisplayInRect using the smallest rectangle that contains the previous and current location of the touch in order to preserve underlying drawings. (I want all drawings to add on to one another like layers.)
I've noticed a strange artifact: When creating a drawing that overlaps with another drawing, Quartz re-draws the rectangle passed into setNeedsDisplayInRect but erases everything below that rectangle.
I suspect that the issue is due to the blending mode, however I experimented with a number of different blending modes and none seemed to do the trick.
How do I draw a path that preserves the underlying content?
Quartz is not a canvas model. It does not keep track of what was drawn in previous loops. Every time drawRect:
is called, it is your responsibility to deal with every pixel in the rectangle you are passed. By default (set in UIView clearsContextBeforeDrawing
), Quartz will clear the rectangle for you, but it's your job to draw the content every time.
If you want to layer things, you either need to put each thing in its own CALayer
or UIView
, or you need to redraw any overlaps each time drawRect:
is called.