gpt4 book ai didi

objective-c - 将图像添加到当前 UIGraphics 上下文

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:33 24 4
gpt4 key购买 nike

我有一个幻灯片放映,允许用户使用简单的绘图工具对幻灯片进行注释。只允许您用手指在屏幕上绘图,然后“保存”。保存功能使用 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;
}
}

这是神奇的保存线:

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

感谢您提供的任何帮助。

更新:

糟糕,我忘了补充,当注释被“保存”时,图像上下文结束,所以我不能使用任何获取当前图像上下文样式的方法。

最佳答案

我通过在开始行和结束行之间添加以下代码实现了这一点:

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);

Context Translate 和 Scales 是必需的,因为将 UIImage 转换为 CGImage 会翻转图像 - 这样做是因为 CGImage 从左下角的原点绘制而 UIImage 从左上角的原点绘制,相同的坐标在翻转比例会导致翻转图像。

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

关于objective-c - 将图像添加到当前 UIGraphics 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6203238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com