我有一个不同尺寸的不同CALayers的UIView。
当我试图将UIView作为图像保存到图库时,它会失去透明度:
我的代码是:
- (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
//获取图片
UIImage *img=[self imageWithView:MainView];
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
注意:当我调试代码时,它会显示透明图像,但是当我在图库中看到它时会显示白色背景
答案 0 :(得分:0)
我已经尝试过你的代码了。您可以尝试以下实施:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *tmpView = [UIView new];
tmpView.frame = self.view.bounds;
tmpView.backgroundColor = [UIColor clearColor];
[self.view addSubview:tmpView];
UIImage *img = [self imageWithView:tmpView];
[self saveInJPGFormat:img];
[self saveInPNGFormat:img];
}
- (void)saveInJPGFormat:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
- (void)saveInPNGFormat:(UIImage *)image {
NSData* imageData = UIImagePNGRepresentation(image);
UIImage* pngImage = [UIImage imageWithData:imageData];
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);
}
- (UIImage *) imageWithView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
您的方法将JPG另存为相机胶卷。 JPG无法保留Alpha通道。 从https://stackoverflow.com/a/10279075/849616获取的第二种方法将图像保存为PNG。我可以打开它,我可以看到图像(保存了alpha通道)。
顺便说一下:这是非常脏和快速的代码。实际上,您应该在UIImage
上为这些方法创建一个类别。同时保持MVC和视图和层都坚持到故事板或分离UIView子类。
我照片库中的图片:
预览屏幕,因此您确定它是空的:
所以这个方法正在运作。