[[[globalSingleton paintingView] drawingView] setOpaque:NO];
[[[[globalSingleton paintingView] drawingView] layer] setOpaque:NO];
[[[globalSingleton paintingView] drawingView] setBackgroundColor:[UIColor clearColor]];
[[[[globalSingleton paintingView] drawingView] layer] setBackgroundColor:[UIColor clearColor].CGColor];
[[[[globalSingleton paintingView] drawingView] layer] renderInContext:ctx];
UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
上面的代码就是我用来将'drawingView'保存到png文件中的代码。我发现了几个问题和答案,所以我应用了它们。我将'drawingView'和drawingView.layer的不透明设置为NO,并将我的'drawingView'的背景颜色设置为[UIColor clearColor]。我想我应用了stackoverflow的所有答案。然而,没有任何改变。 png fil的背景仍然是黑色的。我需要透明的背景,而不是黑色!!
我试过UIImage * image1是否有任何问题。我使用image1在屏幕上显示,然后我可以从该image1找到黑色背景。所以我猜可能在创建image1时有任何问题。
这就是我发现的全部内容。是否有任何可能的解决方案来保存我的透明背景图像的png图像?在此先感谢!!
答案 0 :(得分:8)
哦,天啊!我做的!!我添加了[[UIColor clearColor] set]; 。就是这样。
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
CGContextFillRect(ctx, screenRect);
[[[globalSingleton paintingView] drawingView] setOpaque:NO];
[[[[globalSingleton paintingView] drawingView] layer] setOpaque:NO];
[[[globalSingleton paintingView] drawingView] setBackgroundColor:[UIColor clearColor]];
[[[[globalSingleton paintingView] drawingView] layer] setBackgroundColor:[UIColor clearColor].CGColor];
[[[[globalSingleton paintingView] drawingView] layer] renderInContext:ctx];
UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
答案 1 :(得分:1)
Swift 4.2版本:
extension UIView {
func saveAsImage()-> UIImage? {
UIGraphicsBeginImageContext(self.bounds.size)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
UIColor.clear.set()
context.fill(self.bounds)
self.isOpaque = false
self.layer.isOpaque = false
self.backgroundColor = UIColor.clear
self.layer.backgroundColor = UIColor.clear.cgColor
self.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
}