Drawing erase helper

By July 24, 2012Blog

For one of our app we needed drawing technique that would delete the image in graphics context based on the user input and act like a erase rubber.

Of course there is again everything needed in MonoTouch to do the job.


First we need to get the drawing context of an view object (UIImageView, but can be anything else) and prepare it for the painting. As the CGContext is LL (lower left) coordinates and not UL (upper left) coordinate system, there is a little trick needed to translate the coordinates.

 

public void EraseStart ()
{
	if (drawingBoard == null)
		return;
 
	UIGraphics.BeginImageContext (drawingBoard.Size);
 
	// erase lines
	ctx = UIGraphics.GetCurrentContext ();
 
	// Convert co-ordinate system to Cocoa's (origin in UL, not LL)
	ctx.TranslateCTM (0, drawingBoard.Size.Height);
	ctx.ConcatCTM (CGAffineTransform.MakeScale (1, -1));
 
	ctx.DrawImage (new RectangleF (0, 0, drawingBoard.Size.Width, drawingBoard.Size.Height),
             drawingBoard.CGImage);
}

 

Okay, that was not that bad, so now to the even easier part, to erase the content from the context and put it back to the view so it disappears from the view. To do that we will simply put clip to the context based on the point and we will add it as arc object.

 

public void ContextErasePoint (PointF point, int thickness)
{
	if (drawingBoard == null)
		return;
 
	RectangleF circleRect = new RectangleF (point.X - thickness / 2, 
		drawingBoard.Size.Height - point.Y - thickness / 2, thickness, thickness);
 
	ctx.AddArc (point.X, drawingBoard.Size.Height - point.Y, thickness / 2, 0f, 2f * (float)Math.PI, false);
	ctx.Clip();
 
	ctx.ClearRect (circleRect);
}

 

And now just put the image back from context to the image view so user can see it.

 

public void EraseEnd ()
{
	drawingBoard = UIGraphics.GetImageFromCurrentImageContext ();
	UIGraphics.EndImageContext ();
 
	drawingView.Image = drawingBoard;
}
 

 

That’s it.

Happy coding!

 


 

P.S. There is a sample project to download, with all the goodies working.
P.P.S. If you like my posts, please share the love and tell your friends and support me and buy my apps. Check touch4apps.com for more info. Thank you.

And here is the Github link to the sample code.
And sample video of it in action