将UIView保存为透明背景的png文件

Ric*_*ark 6 png transparent ios

[[[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();
Run Code Online (Sandbox Code Playgroud)

上面的代码就是我用来将'drawingView'保存到png文件中的代码.我发现了几个问题和答案,所以我应用了它们.我将'drawingView'和drawingView.layer的不透明设置为NO,并将'drawingView'的背景颜色设置为[UIColor clearColor].我想我应用了stackoverflow的所有答案.然而,没有任何改变.png fil的背景仍然是黑色的.我需要透明的背景,而不是黑色!!

我试过UIImage*image1是否有任何问题.我使用image1在屏幕上显示,然后我可以从该image1找到黑色背景.所以我猜可以在创建image1时遇到任何问题.

这就是我发现的全部.是否有任何可能的解决方案来保存我的透明背景图像的png图像?提前致谢!!

Ric*_*ark 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();
Run Code Online (Sandbox Code Playgroud)


小智 5

斯威夫特 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
}
}
Run Code Online (Sandbox Code Playgroud)