如何以编程方式截取iPhone的屏幕截图?

问题描述:

在目标C中,我们可以拍摄屏幕截图并在UIImage中存储此图像。

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

您需要创建屏幕大小的位图上下文,并使用

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)

从您的上下文创建一个CGImage。

to create a CGImage from your context.

详细说明:

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];

请注意,如果您运行代码以响应单击UIButton,您的图像将显示按钮。

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