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

标签 ios objective-c cocoa-touch uiview

<分区>

我正在开发一款允许用户将图像放入框架中的应用程序。然后,他们可以使用 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];

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

view hierarchy

高亮显示的UIView就是上面代码中的self.framedImage。 UIImageView 和包含 UIImageView 的 UIButton 都是保存的层次结构的一部分。

我了解使用 UIGraphicsBeginImageContextWithOptions 并将 opaque 标志设置为 NO 意味着 my image must have an alpha channel ,但据我所知,确实如此。 UIView、UIImageView 和 UIButton 都将 [UIColor clearColor] 作为它们的背景色,并且对于所有这三个,Interface Builder 中的“Opaque”复选框都未选中。当我在调试器中检查 View 时,它们的背景颜色的 alpha 值为 0。

我已经尝试在代码中将背景显式设置为 [UIColor clearColor],就在上面的代码片段之前,但它仍然以白色背景保存。我尝试将背景更改为另一种颜色(紫色),并按照我期望的那样保存为紫色背景。所以问题似乎是 UIView 的透明区域被转换为 UIImage 中的不透明白色。

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

最佳答案

多亏了 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];

关于ios - 从 UIView 层次结构创建 UIImage 时背景透明度丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859310/

相关文章:

ios - 包括电话 ://key in info. plist

ios - 弹跳节点变得疯狂

iphone - 如何像 iphone sdk 中的 roambi 应用程序一样顺时针和逆时针旋转饼图

ios - UIControl 跟踪在不同 UIControl 上开始的触摸

objective-c - 如何设置另一个变量/UILabel 变量的引用变量?

objective-c - iPhone/iPad itunes 库读取权限?

ios - 升级到 ios 13 时 xcodebuild 存档失败

iphone - 如何连接 facebook 和 sharekit?

iphone - 无法通过 UINavigationcontroller.viewControllers 更改类的属性

ios - 如何在 iPhone 上以编程方式发送短信?