Monday, September 3, 2012

Taking ScreenShot programmatically in Objective-C

Hi Guyz, in this section i will  show you a custom programmatic method for taking screenshot of any Views within your iOS application and storing it to Photo Library of your device. The custom method i am writing here simply returns UIImage of screen you are capturing, hence use this UIImage as per your requirements.
-(UIImage *) takeAScreenShot {
// here i am taking screen shot of whole UIWindow, but you can have the screenshot of any individual UIViews, Tableviews  . so in that case just use  object of your UIViews instead of  keyWindow.
       UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
     if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) // checking for Retina display   

         UIGraphicsBeginImageContextWithOptions(keyWindow.bounds.size, YES, [UIScreen mainScreen].scale);
       //if this method is not used for Retina device, image will be blurr.

}
    else
    {  UIGraphicsBeginImageContext(keyWindow.bounds.size);

}
    [
keyWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

   // now storing captured image in Photo Library of device
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

/*** if you want to save captured image locally in your app's document directory
       NSData * data = UIImagePNGRepresentation(image);

NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"testImage.png"];
    NSLog(@"Path for Image : %@",imagePath);
    [data writeToFile:imagePath atomically:YES];

*******************************/
     return image;
 }

Note : Include #import <QuartzCore/QuartzCore.h>  for using CALayer property.

No comments:

Post a Comment