Adding an Image to the Current UIGraphics Context

I have a slide show that allows users to comment on slides using a simple drawing tool. It just lets you draw on the screen with your finger and then “save.” The save function uses UIImagePNGRepresentationand works pretty well. I need to figure out how to “continue” existing annotations, so when saving this also takes into account what is already on the slide.

It works using UIImageContext and saves this image context to a file. When an image is saved, it opens to a UIImageView overlay, so if you continue, then your drawing is on an existing png file.

Is there a way to add an existing image to a UIImageContext? Here I control the addition of lines when moving:

- (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 lifeline:

NSData *saveDrawData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
NSError *error = nil;
[saveDrawData writeToFile:dataFilePath options:NSDataWritingAtomic error:&error];

Thanks for any help you can offer.

UPDATE:

Unfortunately, I forgot to add when the annotation is “saved”. The image context is complete, so I cannot use the Get Current Context Image style methods.

+3
source share
1 answer

I achieved this by adding this between my start and end lines:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:saveFilePath];
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);       
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);

, UIImage CGImage - , CGImage UIImage , .

UIGraphicsGetCurrentContext(), , .

+9

All Articles