ios - UIView 的 snapshotView 在没有任何内容的上下文中渲染/绘制

标签 ios objective-c iphone uiview uiimage

我正在尝试在 contex 中渲染/绘制 UIView 的快照 View 以获得 UIImage。然后将其设置为 CAlayer.contents。 我尝试使用此方法获取快照 View :

snapshotViewAfterScreenUpdates:

然后将 UIView 转换为 UIImage:

UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
//I'm trying this method too
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

问题是我正在使用上面的代码,但我得到的是一张空图像。

最佳答案

如果您首先需要快照 UIImage,只需使用第二个代码块中的方法即可。创建一个 UIView 的类别,例如

@implementation UIView (takeSnapshot)

- (UIImage *)takeASnapshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);

    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

够了。您不需要快照 View 并将其转换为图像。在您的情况下,此过程可能会导致问题

关于ios - UIView 的 snapshotView 在没有任何内容的上下文中渲染/绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060767/

相关文章:

ios - 使用 NSPredicate 过滤 NSNumber 的 NSArray 和 NSNumber 的 NSArray

ios - NSParameterAssert 可以留在生产代码中吗?

iphone - Facebook SDK FBLoginView 获取 EXC_BAD_ACCESS

iphone - 需要帮助理解 iOS/Objective-C 编程中的特定分配/发布习惯用法

iphone - 授权 'application-identifier' 具有配置文件不允许的值

iphone - 推送通知徽章不来

ios - 从我的应用程序启动 Mail.app

ios - 无法设置自定义对象的值

objective-c - 为什么仅 setObjectValue :nil is called? 时 NSPopUpButtonCell 就能正确显示

objective-c - 触摸 ImageView 到另一个 ViewController