Take Screenshot of a UIImage iOS

2019-05-31 07:13发布

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.

enter image description here

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.

enter image description here

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.

2条回答
Juvenile、少年°
2楼-- · 2019-05-31 07:27

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;
}
查看更多
对你真心纯属浪费
3楼-- · 2019-05-31 07:43

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];
查看更多
登录 后发表回答