Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to take a screenshot of the iPhone programmatically?

Is it possible in objective C that we can take the screen shot of screen and stored this image in UIImage.

like image 831
user12345 Avatar asked Aug 31 '10 15:08

user12345


2 Answers

The previous code assumes that the view to be captured lives on the main screen...it might not.

Would this work to always capture the content of the main window? (warning: compiled in StackOverflow)


- (UIImage *) captureScreen {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
like image 119
Bill Garrison Avatar answered Sep 22 '22 14:09

Bill Garrison


You need to create a bitmap context of the size of your screen and use

[self.view.layer renderInContext:c]

to copy your view in it. Once this is done, you can use

CGBitmapContextCreateImage(c)

to create a CGImage from your context.

Elaboration :

CGSize screenSize = [[UIScreen mainScreen] applicationFrame].size;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 
CGContextRef ctx = CGBitmapContextCreate(nil, screenSize.width, screenSize.height, 8, 4*(int)screenSize.width, colorSpaceRef, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(ctx, 0.0, screenSize.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

[(CALayer*)self.view.layer renderInContext:ctx];

CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGContextRelease(ctx);  
[UIImageJPEGRepresentation(image, 1.0) writeToFile:@"screen.jpg" atomically:NO];

Note that if you run your code in response to a click on a UIButton, your image will shows that button pressed.

like image 25
VdesmedT Avatar answered Sep 19 '22 14:09

VdesmedT