0

如何在 Xcode 的屏幕上截取指定区域的屏幕截图?

例如,我希望在屏幕上捕获 (0,100,320,200) 的区域并保存到 UIImage 对象?

谢谢

4

1 回答 1

4

尝试下面的代码进行全屏截图(关键窗口)

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];   
UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

尝试此代码以本机分辨率捕获 UIView

CGRect rect = [captureView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[captureView.layer renderInContext:context];   
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

如果您需要,这会将 UIImage 以 jpg 格式以 95% 的质量保存在应用程序的文档文件夹中。

NSString  *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];    
[UIImageJPEGRepresentation(capturedImage, 0.95) writeToFile:imagePath atomically:YES];

资料来源:如何截取 UIView 的屏幕截图?

于 2013-01-11T06:40:54.607 回答