如何在 Swift 中进行全屏截图? [英] How do I take a full screen Screenshot in Swift?

查看:67
本文介绍了如何在 Swift 中进行全屏截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了此代码:

func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

我需要做什么才能将所有其他元素(例如导航栏)添加到屏幕截图中?

What do I need to do to get all the other elements, like the navigation bar, into the screenshots?

推荐答案

与其直接把答案扔在外面,让我解释一下您当前的代码是做什么的,以及如何修改它以捕获全屏.

Instead of just throwing the answer out there, let me explain what your current code does and how to modify it to capture the full screen.

UIGraphicsBeginImageContext(view.frame.size)

这行代码创建了一个与 view 大小相同的新图像上下文.这里需要注意的主要问题是新的图像上下文view的大小相同.除非您想捕获应用程序的低分辨率(非视网膜)版本,否则您可能应该使用 UIGraphicsBeginImageContextWithOptions 代替.然后你可以通过 0.0 获得与设备主屏幕相同的比例因子.

This line of code creates a new image context with the same size as view. The main thing to take away here is that the new image context is the same size as view. Unless you want to capture a low resolution (non-retina) version of your application, you should probably be using UIGraphicsBeginImageContextWithOptions instead. Then you can pass 0.0 to get the same scale factor as the devices main screen.

view.layer.renderInContext(UIGraphicsGetCurrentContext())

这行代码会将视图的图层渲染到当前图形上下文(即您刚刚创建的上下文)中.这里要带走的主要内容是只有 view(及其子视图)被绘制到图像上下文中.

This line of code will render the view's layer into the current graphics context (which is the context you just created). The main thing to take away here is that only view (and its subviews) are being drawn into the image context.

let image = UIGraphicsGetImageFromCurrentImageContext()

这行代码根据已绘制到图形上下文中的内容创建一个 UIImage 对象.

This line of code creates an UIImage object from what has been drawn into the graphics context.

UIGraphicsEndImageContext()

这行代码结束了图像上下文.它已清理(您创建了上下文并且也应该将其删除.

This line of code ends the image context. It's clean up (you created the context and should remove it as well.

结果是一张与 view 大小相同的图像,其中包含 view 及其子视图.

The result is an image that is the same size as view, with view and its subviews drawn into it.

如果要将所有内容都绘制到图像中,那么您应该创建一个与屏幕大小相同的图像,并将屏幕上的所有内容都绘制到其中.实际上,您可能只是在谈论应用程序关键窗口"中的所有内容.由于UIWindowUIView 的子类,因此它也可以绘制到图像上下文中.

If you want to draw everything into the image, then you should create an image that is the size of the screen and draw everything that is on screen into it. In practice, you are likely just talking about everything in the "key window" of your application. Since UIWindow is a subclass of UIView, it can be drawn into a image context as well.

这篇关于如何在 Swift 中进行全屏截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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