将图像添加到当前的UIGraphics上下文

Dan*_*nly 3 objective-c uiimageview

我有一个幻灯片,允许用户使用简单的绘图工具注释幻灯片.只需让您用手指在屏幕上绘图然后"保存"即可.保存功能使用UIImagePNGRepresentation并且运行良好.我需要解决的是如何"继续"现有注释,以便在保存发生时它还会考虑幻灯片上已有的内容.

它使用UIImageContext并将该图像上下文保存到文件中.保存图像时,它会打开覆盖UIImageView,因此如果您"继续",则将图形绘制到现有的png文件中.

有没有办法可以将现有图像添加到UIImageContext?在这里,我控制运动时添加的线条:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是神奇的储蓄线:

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

谢谢你尽你所能的帮助.

更新:

哎呀我忘了添加,当注释被"保存"时,图像上下文结束,所以我不能使用任何获取当前图像上下文样式的方法.

Dan*_*nly 9

我通过在开始和结束行之间添加它来实现这一点:

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);
Run Code Online (Sandbox Code Playgroud)

Context Translate和Scales是必要的,因为将UIImage转换为CGImage会翻转图像 - 这样做是因为CGImage从左下角绘制而UIImage从左上角绘制,同样的坐标在翻转的比例结果上在翻转图像中.

因为我将现有图像绘制到UIGraphicsGetCurrentContext()保存文件时,所以会考虑到这一点.