gpt4 book ai didi

ios - 在不呈现/显示 UIView 的情况下将 UIVIew 转换为 UIImage

转载 作者:行者123 更新时间:2023-11-29 00:44:50 25 4
gpt4 key购买 nike

我正在使用方法将 UIView 转换为 UIImage ,当 UIView (要转换为 UIImage)已经存在/显示时,它做得很好。但我的要求是将UIView转换为UIImage而不显示UIView。不幸的是,这段代码在这种情况下失败了,我陷入了困境。任何帮助将不胜感激。

我正在使用以下方法:

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

最佳答案

您的代码可能会失败,因为您没有布置 View 的 subview (当您将 View 添加为 subview 时,这是自动完成的)。尝试类似我在下面写的方法:

+ (UIImage *)imageFromView:(UIView *)view sized:(CGSize)size
{
// layout the view
view.frame = CGRectMake(0, 0, size.width, size.height);
[view setNeedsLayout];
[view layoutIfNeeded];

// render the image
UIGraphicsBeginImageContextWithOptions(size, view.opaque, 0.0f);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return renderedImage;
}

关于ios - 在不呈现/显示 UIView 的情况下将 UIVIew 转换为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com