Take Screenshot of a UIImage iOS

2019-05-31 06:48发布

问题:

I want to take screenshot of a perticular section of my screen in a iOS App. The attached image is that part of screen. Here I want to take screenshot of the red marked rectangular area containing 3 UIImageViews which contains a white Image Frame at background , an image with coffee cup and the apple sign image on the coffee respectively.

I am using the following code for doing that...

- (UIImage *)captureView:(UIView *)view withArea:(CGRect)screenRect {

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [view.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage ;
}

Calling it like this

UIImage *viewImage = [self captureView:self.FrameImageView withArea:self.FrameImageView.bounds];

Here FrameImageView is an UIImageView that contains the white Image frame at the background.

But I am getting the resulting image like the following.

I think the problem is , my code is taking screenshot of the layer of FrameImageView. That's why I am getting the background frame only. But I want the screenshot to contain the other 2 UIImageViews over FrameImageView as well like the first image's red rectangle section.

can anyone help me , how to fix that. Thanks in Advance.

回答1:

Try this variant

 UIGraphicsBeginImageContextWithOptions(FrameImageView.frame.size, YES, 4);

 [_myStreetView drawViewHierarchyInRect:FrameImageView.frame afterScreenUpdates:YES];

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

 UIImageView *img = [[UIImageView alloc] initWithImage:image];


回答2:

Try this:

- (UIImage*)captureView:(UIView *)yourView {
    CGRect rect = [[UIScreen mainScreen] bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [yourView.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}