Rendering UIView with its children

前端 未结 2 1238
北恋
北恋 2020-12-08 15:33

I have a UIView that has an image and some buttons as its subviews. I\'d like to get a \"snapshot\" image of it using renderInContext, or other met

相关标签:
2条回答
  • 2020-12-08 15:47

    The simple 4-line version didn't work for me. I have a UIView (with sublayers), and a child UITextView. I can render the UIView into the UIImage OK, but the child UITextView does not get rendered.

    My simple solution is as follows:

    CGRect rect = [view bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [view.layer renderInContext:context];
    for (UIView *sv in view.subviews)
    {
        CGContextTranslateCTM(context, sv.frame.origin.x, sv.frame.origin.y);
        [sv.layer renderInContext:context];
        CGContextTranslateCTM(context, -sv.frame.origin.x, -sv.frame.origin.y);
    }
    
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    Note that the simple use of CGContextTranslateCTM assumes the child views have no transform other than translation. Also I'm assuming the child views are entirely contained within the parent view frame.

    0 讨论(0)
  • 2020-12-08 15:51

    Try something like this:

    UIGraphicsBeginImageContext(clefView.bounds.size);
    [clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    0 讨论(0)
提交回复
热议问题