如何在 iOS 上以编程方式截取屏幕截图 [英] How to take a screenshot programmatically on iOS

查看:33
本文介绍了如何在 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 尊重原始答案!

使用QuartzCore

#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");
}

<小时>

在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆