I’ve got a slideshow that allows users to annotate slides with a simple drawing tool. Just allows you to draw on the screen with your finger and then ‘save’. The save feature uses UIImagePNGRepresentation and works rather well. What I need to work out is how to ‘continue’ existing annotations so when a save happens it also takes into account what is already on the slide.
It works using UIImageContext and saving that image context into a file. When an image is saved it opens onto an overlay UIImageView, so if you are ‘continuing’ then your drawing onto an existing png file.
Is there a way I can add an existing image to the UIImageContext? Here I control the addition of the lines upon movement:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(drawToggle){
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 40;
//Define Properties
[drawView.image drawInRect:CGRectMake(0, 0, drawView.frame.size.width, drawView.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinBevel);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
//Start Path
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
//Save Path to Image
drawView.image = UIGraphicsGetImageFromCurrentImageContext();
lastPoint = currentPoint;
}
}
Here is the magic saving line:
NSData *saveDrawData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
NSError *error = nil;
[saveDrawData writeToFile:dataFilePath options:NSDataWritingAtomic error:&error];
Thanks for any help you can offer.
UPDATE:
Oops I forgot to add, when an annotation is ‘saved’ the Image Context is ended, so I can’t use any Get Current Image Context style methods.
I achieved this by adding this between my Start and End lines:
The Context Translate and Scales are necessary because converting a UIImage to a CGImage flips the image – it does this because a CGImage draws from a bottom left origin and the UIImage draws from a top left origin, the same co-ordinates on a flipped scale results in a flipped image.
Because I drew the existing image into the
UIGraphicsGetCurrentContext()when I save the file it’ll take this into account.