Erasing after drawing with CGContext
Asked Answered
S

3

10

I'm trying to do a simple drawing app for the iPad where you can draw on a picture, and I'm using CGContext stuff to do it but the way I originally planned on handling erasing was to just draw over stuff with white...except I just realized today that it doesn't work when you're drawing onto another image because then when you "erase" you'll also "erase" the background image as well.

Is there any way to support actual erasing?

Thanks!

Skiffle answered 9/5, 2011 at 15:31 Comment(0)
S
4

Display the user's drawing in a layer above the image. Then erasing is as simple as drawing a transparent patch on the drawing layer in order to let the image pixels below it show through.

Siusiubhan answered 12/5, 2011 at 23:0 Comment(3)
How do you draw a transparent patch? I have used CGContextSetRGBStrokeColor with an alpha of 0.0, but that doesn't seem to work.Drachma
Play with the compositing mode (Copy instead of SourceIn, for example) and consider filling as well as stroking.Siusiubhan
This is a nothing-burger. Should be a comment, not an answer.Haubergeon
I
26

I also needed erasing functionality. Based on @Jeremy's answer, here is what worked for me:

CGContextRef cgref = UIGraphicsGetCurrentContext();

if(erase == TRUE) // Erase to show background
{
    CGContextSetBlendMode(cgref, kCGBlendModeClear);
}
else // Draw with color
{
    CGContextSetBlendMode(cgref, kCGBlendModeNormal);
}
Interbreed answered 28/1, 2012 at 8:35 Comment(3)
you are my hero, thank you so much for giving such a simple solution!Interdictory
First off I'm going by Ray Wenderlich's tutorial for creating a simple drawing app. Everything works for it, but when I change the blend mode to kCGBlendModeClear all it does is erase the whole canvas once touches ended gets called. Any thoughts?Ketose
Excellent, though too verbose. You can do the same with a one-liner: CGContextSetBlendMode(UIGraphicsGetCurrentContext(), erase ? kCGBlendModeClear : kCGBlendModeNormal);Lutanist
S
4

Display the user's drawing in a layer above the image. Then erasing is as simple as drawing a transparent patch on the drawing layer in order to let the image pixels below it show through.

Siusiubhan answered 12/5, 2011 at 23:0 Comment(3)
How do you draw a transparent patch? I have used CGContextSetRGBStrokeColor with an alpha of 0.0, but that doesn't seem to work.Drachma
Play with the compositing mode (Copy instead of SourceIn, for example) and consider filling as well as stroking.Siusiubhan
This is a nothing-burger. Should be a comment, not an answer.Haubergeon
C
0

Clear all CGContextRef drawings:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.bounds);
[self setNeedsDisplay];
Cassino answered 19/7, 2020 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.