截取当前在iOS上不显示的视图的屏幕截图 [英] Taking a screenshot of a view that is currently not on screen on iOS
问题描述
我正在尝试在两个ViewController之间进行转换.我的Transition类具有目标视图控制器的属性.当我尝试获取目标视图的屏幕截图时,我使用以下方法:
I'm trying to make a transition between two ViewControllers. My Transition class has a property for the destination view controller. When I try to get a screenshot of the destination's view, I use this method:
+ (UIImage *)renderImageFromView:(UIView *)view withRect:(CGRect)frame {
// Create a new context the size of the frame
UIGraphicsBeginImageContextWithOptions(frame.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Render the view
[view.layer renderInContext:context];
// Get the image from the context
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
// Cleanup the context you created
UIGraphicsEndImageContext();
return renderedImage;
}
因此,当我想要图像时,我将执行以下操作:
So when I want the image, I'll do this:
UIImage *image = [UIImage renderImageFromView:destinationController.view withRect:destinationController.view.bounds];
我在带有橙色背景色和标签的空白UIViewController上尝试过.我得到了橙色背景色,但是没有得到在IB中创建的标签.有没有办法获取我计划显示的新视图的适当屏幕截图?谢谢!
I tried it on a blank UIViewController with an orange background color and a label. I get the orange background color, but I do not get the label that was created in IB. Is there a way to get a proper screenshot of the new view I plan on showing? Thanks!
推荐答案
您需要确保将视图的图层绘制到第一层.在 CALayer
上调用renderInContext只会递归地调用其他子 CALayer
.您需要您的孩子 UIView
进行绘制,而不仅仅是使用 CALayer
.
You need to make sure the view's layer is drawn to first. Calling renderInContext on a CALayer
will only recursively call additional child CALayer
s. You need your child UIView
s to draw themselves, not just using the CALayer
.
尝试致电
[view drawrect:frame];
代替
[view.layer renderInContext:context];
只要您具有打开的图形上下文(此时需要执行此操作), drawrect
就应该直接在其中绘制图形.
As long as you have an open graphics context(which you do at that point), drawrect
should draw directly into that.
这篇关于截取当前在iOS上不显示的视图的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!