如何用透明笔画保存图像

我跟着@Rob的答案和绘制,因为我想…但是当我保存这个图像….笔画不透明了

Objective-C如何避免在UIBezierPath的笔触颜色上绘制相同颜色的图像

为了保存图像我写了这个代码

在这里输入图像说明

-(void)saveImage { UIGraphicsBeginImageContextWithOptions(self.upperImageView.bounds.size, NO, 0); if ([self.upperImageView respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) [self.upperImageView drawViewHierarchyInRect:self.upperImageView.bounds afterScreenUpdates:YES]; // iOS7+ else [self.upperImageView.layer renderInContext:UIGraphicsGetCurrentContext()]; // pre iOS7 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndPDFContext(); UIImageWriteToSavedPhotosAlbum(self.upperImageView.image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil); } 

您要么将图像视图的alpha值设置为某处的path为1.0,要么使用不允许透明度的值(例如, UIGraphicsBeginImageContextWithOptions对于opaque参数为YES ,或将映像暂存为不保留的格式alpha,如JPEG)。

一些额外的想法:

  1. 我注意到你只绘制了upperImageView 。 如果您想要复合图像,则需要同时绘制两者。 或者你只是试图保存一个图像视图?

    (对那些不熟悉这个问题的人来说,整个问题的关键是如何在图像上绘制多条path,并且使用相同的缩小阿尔法来完整地设置这些path,而不是让path的交点导致一些附加的行为。是通过有两个不同的图像视图来完成的,一个是底层图像,一个是绘制的path,这个问题的答案的关键是应该绘制100%alpha的path,但是增加一个图层一个观点,本身,减less阿尔法。)

  2. 什么是你正在绘制的图像视图的alpha

    注意:在另一个问题的答案中,保存组合path的临时副本。 我们不得不暂时将alpha设置为1.0。 但是,在保存最终结果的时候,我们希望将“path”图像视图的alpha值保持在较小的值。

  3. 不相关的,但你忠实地转录了我原来的例子中,我不小心调用UIGraphicsEndPDFContext而不是UIGraphicsEndImageContext错字(从固定)。 你应该使用后者。

所以,考虑两个图像视图,一个与照片和一个与绘制的path,分别称为imageImageView (1.0的alpha )和pathsImageView (与0.5的alpha ),我可以像这样保存快照:

 - (void)saveSnapshot { CGRect rect = self.pathsImageView.bounds; UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0); if ([self.pathsImageView respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { [self.imageImageView drawViewHierarchyInRect:rect afterScreenUpdates:YES]; // iOS7+ [self.pathsImageView drawViewHierarchyInRect:rect afterScreenUpdates:YES]; } else { [self.imageImageView.layer renderInContext:UIGraphicsGetCurrentContext()]; // pre iOS7 [self.pathsImageView.layer renderInContext:UIGraphicsGetCurrentContext()]; } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); } 

当我这样做时,由此产生的合成图像在我的相册:

图片在相册中