Image from UIView

2019-01-11 07:43发布

问题:

is there any Possibility to create a image out of a UIView?

Thanks, Andreas

回答1:

#import "QuartzCore/QuartzCore.h" after you added the framework to your project. Then do:

UIGraphicsBeginImageContext(yourView.frame.size);
[[yourView layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// The result is *screenshot


回答2:

I have used the answer to improve it even further. Unfortunately, the original code only produced a mirrored image.

So here's the working code:

- (UIImage *) imageFromView:(UIView *)view {

    UIGraphicsBeginImageContext(view.frame.size);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, 0, view.size.height);
    // passing negative values to flip the image
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    [[appDelegate.scatterPlotView layer] renderInContext:currentContext];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshot;
}