Taking a screenshot of a view that is currently not on screen on iOS

女生的网名这么多〃 提交于 2019-12-21 20:04:48

问题


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];

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!


回答1:


You need to make sure the view's layer is drawn to first. Calling renderInContext on a CALayer will only recursively call additional child CALayers. You need your child UIViews to draw themselves, not just using the CALayer.

Try calling

[view drawrect:frame]; 

instead of

[view.layer renderInContext:context];

As long as you have an open graphics context(which you do at that point), drawrect should draw directly into that.



来源:https://stackoverflow.com/questions/13979067/taking-a-screenshot-of-a-view-that-is-currently-not-on-screen-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!