如何在iOS上以编程方式拍摄屏幕截图 [英] How to take a screenshot programmatically on iOS
本文介绍了如何在iOS上以编程方式拍摄屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将屏幕上的图像的屏幕快照保存到保存的照片库中.
I want a screenshot of the image on the screen saved into the saved photo library.
推荐答案
我正在回答这个问题,因为它受到了高度重视,并且答案很多,还有Swift和Obj-C.
I'm answering this question as it's a highly viewed, and there are many answers out there plus there's Swift and Obj-C.
免责声明 这不是我的代码, 也不是我的答案, 这只是为了帮助住在这里的人快速找到回答.有指向原始答案的链接,可在应得的信用额中给予功劳! 如果您使用原始答案,则请以+1表示原始答案!
#import <QuartzCore/QuartzCore.h>
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.window.bounds.size);
}
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
if (imageData) {
[imageData writeToFile:@"screenshot.png" atomically:YES];
} else {
NSLog(@"error while taking screenshot");
}
In Swift
func captureScreen() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
注意: 由于编程的本质, 可能需要进行更新,因此请编辑或让我知道! *此外,如果我未能包含值得包括在内的答案/方法,也请随时告诉我!
Note: As the nature with programming, updates may need to be done so please edit or let me know! *Also if I failed to include an answer/method worth including feel free to let me know as well!
这篇关于如何在iOS上以编程方式拍摄屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文