如何在Swift中保存视图及其子视图的屏幕截图? [英] How to save screenshot of a view with its subviews in Swift?

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

问题描述

我想捕获一个带有子视图的视图。我正在使用以下代码捕获屏幕:

I want to capture a view with its subviews. I'm using this code to capture the screen:

let view = self.faceTrackerContainerView

UIGraphicsBeginImageContext(CGSizeMake(view.bounds.size.width, view.bounds.size.height))
UIGraphicsGetCurrentContext()!
self.view?.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

这些代码捕获整个屏幕,包括位于视图前面的按钮。我尝试了以下代码,但只捕获了主视图,但不包括子视图:

These codes capture the whole screen including a button that's in front of the view. I tried these codes but it only captures the main view excluding its subviews:

let view = self.faceTrackerContainerView
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale);

view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

我还尝试了 snapshotViewAfterScreenUpdates(true)从这里开始,但我不知道如何实现它。我在视图下方有一个collectionView,在视图上方有一个按钮(两者均不在视图中)。第一个代码使用按钮,collectionView和子视图捕获所有内容。第二个代码捕获不带子视图的视图。我缺少什么?

I also tried the snapshotViewAfterScreenUpdates(true) from here but I don't know how to implement it. I have a collectionView below the view and a button on top of the view (both are not in the view). The first codes capture everything with the button, collectionView, and subviews. The second codes capture the view without the subviews. What am I missing?

推荐答案

这对我有用,

func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(faceTrackerContainerView.frame.size)
    faceTrackerContainerView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

参考

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

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