如何通过代码(在Swift中)从屏幕上截取屏幕截图并保存?我可以截取屏幕截图并将其另存为图像吗?
我已经看过并且看到了这段代码,但是我不能使用它(我认为),因为它什么也没做。
var screen = UIScreen.mainScreen() snapshotVieww = screen.snapshotViewAfterScreenUpdates(false) UIGraphicsBeginImageContextWithOptions(screen.bounds.size, false, 0) snapshotVieww.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true) var image:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() provino = UIImageView(image: image)
使用Swift 4 / iOS 10.3,您可以选择以下方式之一来解决您的问题。
以下代码显示如何拍摄屏幕截图并将其保存在设备相册中:
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0) guard let context = UIGraphicsGetCurrentContext() else { return } view.layer.render(in: context) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
请注意,此代码的结果将是.JPG图像。另请注意,导航栏和状态栏不会出现在最终图像中。
从iOS 10开始,作为以前代码的替代方法,您可以使用以下代码:
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage let renderer = UIGraphicsImageRenderer(size: view.frame.size) let image = renderer.image(actions: { context in view.layer.render(in: context.cgContext) }) //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
如果要截取包含导航栏(但不包括状态栏)的屏幕截图,则可以使用以下代码:
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage guard let layer = UIApplication.shared.keyWindow?.layer else { return } UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0) guard let context = UIGraphicsGetCurrentContext() else { return } layer.render(in: context) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
import UIKit class ViewController: UIViewController { /* ... */ @IBAction func screenshot(_ sender: UIBarButtonItem) { //Create the UIImage guard let layer = UIApplication.shared.keyWindow?.layer else { return } let renderer = UIGraphicsImageRenderer(size: layer.frame.size) let image = renderer.image(actions: { context in layer.render(in: context.cgContext) }) //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } }
从iOS 10开始,为了防止您的应用在调用screenshot(_:)方法时崩溃,您需要将密钥添加NSPhotoLibraryUsageDescription到项目的Info.plist文件中:
screenshot(_:)
NSPhotoLibraryUsageDescription
<key>NSPhotoLibraryUsageDescription</key> <string>Some description to explain why access is required</string>