How to take a screenshot of a part of an app's

2019-05-26 03:11发布

问题:

I'm trying to save a screenshot of a part of the screen with all views and layers merged. The only way I know how to do this is with the code below.

The code below creates an 80x80 square, but with a top left corner at 0,0.

How can I cut a smaller rectangle out of a full page screenshot? For example I have a 320x480 full window screenshot, but I only need an 80x80 square centered at 160,240?

UIGraphicsBeginImageContext(smallView.frame.size);
[appDelegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Thank you!

回答1:

after getting the screenshot image crop the required part using this

CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], cropRect);
UIImage *result = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);


回答2:

Untested suggestion...

    UIGraphicsBeginImageContext(smallView.frame.size);
    [appDelegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];

    CGRect cropRect = UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    CGRectMake(160.0,240.0,smallView.frame.size.width,smallView.frame.size.height);
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect(screenshot.CGImage,cropRect);
    UIImage *croppedScreenshot = [UIImage imageWithCGImage:croppedImageRef];
    CGImageRelease(croppedImageRef);
    UIGraphicsEndImageContext();