[英]save UIView as png file with transparent background
[[[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图像? 提前致谢!!
天啊! 我做的!! 我添加了[[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();
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.