屏幕上没有的VC的屏幕截图

时间:2017-01-27 00:14:26

标签: ios swift uiviewcontroller screenshot

我需要截取一个视​​图的截图,该视图是另一个不在屏幕上的视图控制器的一部分。

我相信我需要创建该VC,用正确的数据填充它,“渲染它”然后截取屏幕截图,我该怎么办?

这是我当前的代码,它从目标VC触发viewDidLoad()但是生成一个空白图像:

    var query = {
          index: 'firebase',
          type: 'student',
          "body": {
            "query": {
              "bool": {
                "must": [ 
       {
        "nested": {
          "path": "subjects",
          "query": {
            "bool": {
              "must": [
                { "exists": { "field": english } }
              ]
            }
          }
        }
      }

    ]

提前谢谢

1 个答案:

答案 0 :(得分:0)

经过一些工作,我设法找到了一个解决方案,它可能不是最好的解决方案,所以如果有人有更好的方法,我会很感激。

我在当前视图控制器中添加了一个视图,因此我可以将目标视图添加到其中。我捕获图像,然后删除我添加的视图,这样当前的VC看起来就像它一样。

func share(sender:UIBarButtonItem){

    // Create the VC that has the view we are going to share
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "ShareVC") as! ShareTransactionViewController
    vc.transaction = self.transaction

    // Prepare the image context
    UIGraphicsBeginImageContextWithOptions(self.snap.bounds.size, true, 0.0)

    // Draw the view we want to share from the created VC into the current VC
    vc.view.drawHierarchy(in: self.snap.bounds, afterScreenUpdates: true)

    // Adds the view from the other vc to the snap of the current VC
    self.snap.insertSubview(vc.view, at:0)

    // Redraws all the views of this vc
    self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)

    // Defining the variable for activityItems
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    let imageToShare = [ image ]
    let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)

    // set up activity view controller
    activityViewController.popoverPresentationController?.sourceView = self.view  // so iPads won't crash

    // Present the view controllet that shares the content
    self.present(activityViewController, animated: true, completion: nil)

    // Removes added subview in current VC
    for view in self.snap.subviews {
        view.removeFromSuperview()
    }

}