Take Screenshot of a UIImage iOS

僤鯓⒐⒋嵵緔 提交于 2020-02-29 06:30:07

问题


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;
}


来源:https://stackoverflow.com/questions/20298887/take-screenshot-of-a-uiimage-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!