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

9
[[[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文件的背景仍然是黑色的。我需要透明的背景,而不是黑色的!

我尝试了是否有UIImage *image1的问题。我使用image1在屏幕上显示,然后我可以从那个image1中找到黑色的背景。所以我可以猜测在创建image1时存在任何问题。

这就是我发现的全部内容。有没有可能解决我的png图像与透明背景图像一起保存的问题?提前谢谢!

2个回答

9

哦,天啊!我做到了!!我加入了[[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();

这是否保留了 Alpha 通道? - Hemant Bavle

5

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
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接