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

查看:191
本文介绍了如何在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 <相同大小的新图像上下文/ code>。这里要带走的主要是新图像上下文 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.

结果是一个相同的图像大小为查看,其中查看及其子视图。

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

如果你想在图像中绘制所有内容,那么你应该创建一个与屏幕大小相同的图像,并将屏幕上的所有内容绘制到屏幕中。实际上,你可能只是在谈论应用程序的关键窗口。由于 UIWindow UIView 的子类,因此可以将其绘制到图像上下文中好吧。

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天全站免登陆