Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture UIView as UIImage

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?

like image 650
Srikar Appalaraju Avatar asked Aug 24 '11 14:08

Srikar Appalaraju


People also ask

How do I render UIView to UIImage?

extension UIView { // Using a function since `var image` might conflict with an existing variable // (like on `UIImageView`) func asImage() -> UIImage { if #available(iOS 10.0, *) { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer. image { rendererContext in layer. render(in: rendererContext.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in .

What is UIImage?

An object that manages image data in your app.


1 Answers

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);
like image 96
pgb Avatar answered Oct 13 '22 09:10

pgb