Flatten UIViews Subviews to UIImage iPhone 3.0

2019-03-13 21:47发布

问题:

I have a UIView that has several UIImageViews as subviews. Each of these subviews has had different affine transform applied. I would like to take what amounts to a screen capture of my UIView, capturing it as a UIImage, or some other image representation.

The method I have tried already, rendering the layers to a CGContext with:

[view.layer renderInContext:UIGraphicsGetCurrentContext()];

doesn't preserve the positioning or other affine transformations of my subviews.

I would really appreciate a kick in the right direction.

回答1:

Try this:

UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


回答2:

Here's a Swift 2.x version:

// This flattens <allViews> into single UIImage
func flattenViews(allViews: [UIView]) -> UIImage? {
    // Return nil if <allViews> empty
    if (allViews.isEmpty) {
        return nil
    }

    // If here, compose image out of views in <allViews>
    // Create graphics context
    UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)

    // Draw each view into context
    for curView in allViews {
        curView.drawViewHierarchyInRect(curView.frame, afterScreenUpdates: false)
    }

    // Extract image & end context
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Return image
    return image
}