从UIView层次结构创建UIImage时,背景透明度丢失。

3
我正在开发一个应用程序,允许用户将图像放入框架中。然后他们可以使用iOS共享表单以某种方式分享该图像。我的问题是框架有圆角,但当我通过保存图像到相机胶卷来测试时,背景是白色而不是透明的,我无法弄清楚如何使其保存为带有透明背景的图像。
这是我的代码:
UIGraphicsBeginImageContextWithOptions(self.framedImage.bounds.size, NO, 0.0f);
[self.framedImage drawViewHierarchyInRect:self.framedImage.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//present the system share sheet for the image
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[image] applicationActivities:nil];

这是我的视图层次结构,来自Xcode的视图调试器:

view hierarchy

上面代码中突出显示的UIView是self.framedImage。UIImageView和包含UIImageView的UIButton都是保存层次结构的一部分。
我知道使用UIGraphicsBeginImageContextWithOptions并将opaque标志设置为NO意味着我的图像必须具有alpha通道,但就我所见,它确实具有。UIView、UIImageView和UIButton的背景颜色都是[UIColor clearColor],对于所有三个视图,在Interface Builder中,“Opaque”复选框都未被选中。当我在调试器中检查这些视图时,它们的背景颜色的alpha值都为0。
我已经尝试在上面的片段之前在代码中明确设置背景为[UIColor clearColor],但它仍然带有白色背景保存。我尝试将背景更改为另一种颜色(紫色),保存的结果是我期望的带有紫色背景。因此,问题似乎是UIView的透明区域被转换为UIImage中的不透明白色。

有人知道我这里缺少了什么吗?


3
这是一个愚蠢的问题,只是为了确认一下:您是否正在以支持透明度的格式保存图像? - Sergey Kalinichenko
2
哎呀!我正在展示系统共享表,当按下“保存到相机胶卷”时,会将图像保存为JPEG格式。该格式不支持透明度。谢谢! - neilgmacy
1
不用谢!如果代码适用于其他格式(我认为应该适用,因为你的一切看起来都没问题),可以考虑删除问题,因为问题已经无法再现了。 - Sergey Kalinichenko
NSData *pngImageData = UIImagePNGRepresentation(image); UIImage *imgTransperentBG = [UIImage imageWithData:pngImageData]; UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil); 这段代码对我来说是有效的。 - Hardik Darji
1个回答

11

感谢dasblinkenlight的评论,我能够找到问题所在。

我将UIImage传递给UIActivityViewController,以便呈现系统共享表单。但是,当我按下“保存图像”按钮将图像保存到相机胶卷时,默认情况下会保存为jpeg格式,而不支持透明度。在将图像传递给UIActivityViewController之前将其转换为PNG解决了问题。

这是修复后的代码:

UIGraphicsBeginImageContextWithOptions(self.framedImage.bounds.size, NO, 0.0f);
[self.framedImage drawViewHierarchyInRect:self.framedImage.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//convert to PNG
NSData *pngImageData = UIImagePNGRepresentation(image);

//present the system share sheet for the PNG data
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[pngImageData] applicationActivities:nil];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接