Howe to capture UIView top UIView

You can take a screenshot of any view or whole screen of the iPhone app with below method

- (UIImage *)captureView {

//hide controls if needed
CGRect rect = [self.view bounds];

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;

}

And call it like bellow…

UIImage *tempImageSave=[self captureView];

and you can also save this image with this bellow line for photo album..

UIImageWriteToSavedPhotosAlbum(tempImageSave,nil,nil,nil);

and you can also save this image with this bellow line for Document Directory..

NSData *imageData = UIImagePNGRepresentation(tempImageSave);
NSFileManager *fileMan = [NSFileManager defaultManager];

NSString *fileName = [NSString stringWithFormat:@"%d.png",1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[fileMan createFileAtPath:pdfFileName contents:imageData attributes:nil];

If the view contains the layer images or some graphics related data then use below method.

-(UIImage *)convertViewToImage:(UIView *)viewTemp
{
    UIGraphicsBeginImageContext(viewTemp.bounds.size);
    [viewTemp drawViewHierarchyInRect:viewTemp.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;

}

And use this method like below.

UIImage *tempImageSave = [self convertViewToImage:yourView];

I hope this helpful for you.

Leave a Comment