将UIView保存到透明的PNG中

时间:2011-01-19 14:12:34

标签: uiview png transparent iphone

我有一个UIView,我希望它存储为透明的PNG,即没有UIVIew背景颜色......

我目前正在使用此代码,但它的工作正常,但背景颜色为:(

UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:filePath atomically:YES];

那么有没有人知道如何将这个图像作为透明图像?

提前谢谢..

4 个答案:

答案 0 :(得分:9)

就我而言,我忘记了不透明的财产。它应该设置为NO:

view.opaque = NO;

答案 1 :(得分:7)

将背景颜色更改为[UIColor clear],绘制图像,然后将背景颜色设置回原始颜色。

由于GUI更新仅在下一个runloop循环中触发,因此用户不应该看到任何闪烁。

UIColor* color=self.backgroundColor;
view.backgroundColor=[UIColor clearColor];

UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:filePath atomically:YES];

self.backgroundColor=color;

答案 2 :(得分:3)

作为吉拉德答案的补充。在视网膜显示器上,这可能会导致一些质量问题。要获取视网膜上下文,您可以使用this帖子中的此代码。

UIColor* color=self.backgroundColor;
view.backgroundColor=[UIColor clearColor];

// This is for retina render check
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(YourView.frame.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(keyWindow.bounds.size);
// And it goes up to here the rest stays the same

[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:filePath atomically:YES];

self.backgroundColor=color;

答案 3 :(得分:0)

对于Objective-c,您必须设置opaque = NO

 + (UIImage *) imageWithView:(UIView *)view 
    {     
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [[UIScreen mainScreen] scale]);     
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];     
        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();     
        UIGraphicsEndImageContext();     
        return img; 
    }

对于Swift,您必须设置opaque = false

func imageWithView(inView: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(inView.bounds.size, false, 0.0)
        if let context = UIGraphicsGetCurrentContext() {
            inView.layer.render(in: context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }