Capture UIView as UIImage

2019-01-31 13:24发布

I have been using this method to convert a UIView into UIImage. i.e. screen snapshot of a view -

@interface UIView(Extended) 

- (UIImage *) imageByRenderingView;

@end


@implementation UIView(Extended)


- (UIImage *)imageByRenderingView
{   
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

@end

To use it, I do this -

UIImage *currImage = [self.view imageByRenderingView];

This gives the image representation of the entire UIView. Now I want 2 images, one is of the top half of the UIView and the other is the bottom half. How do I do that?

1条回答
戒情不戒烟
2楼-- · 2019-01-31 13:45

You can split your UIImage in two by using this code:

CGImageRef topOfImageCG =
         CGImageCreateWithImageInRect(currImage.CGImage,
                                      CGRectMake(0,
                                                 0,
                                                 currImage.size.width,
                                                 currImage.size.height / 2.0));

UIImage *topOfImage = [UIImage imageWithCGImage:topOfImageCG];

CGImageRelease(topOfImageCG);
查看更多
登录 后发表回答