nei*_*acy 2 cocoa-touch objective-c uiview ios
我正在开发一个应用程序,让用户将图像放在一个框架中.然后,他们可以使用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];
Run Code Online (Sandbox Code Playgroud)
这是我的视图层次结构,来自Xcode的视图调试器:
突出显示的UIView self.framedImage位于上面的代码中.UIImageView和包含UIImageView的UIButton都是保存的层次结构的一部分.
我知道使用设置为NO UIGraphicsBeginImageContextWithOptions的opaque标志意味着我的图像必须有一个alpha通道,但据我所知,它确实如此.UIView,UIImageView和UIButton都有[UIColor clearColor]它们的背景颜色,对于这三个,Interface Builder中的"不透明"复选框是未选中的.当我在调试器中检查视图时,它们的背景颜色的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];
Run Code Online (Sandbox Code Playgroud)