2017-04-07 124 views
1

我有一個父視圖的多個子視圖,我需要將uiview轉換爲uiimage,但只有某些子視圖。所以我給我需要截圖的視圖添加了一個標籤,並將其添加到了它自己的視圖中,但是當我嘗試截圖時,我會看到一個黑屏。但是,當我使用常規父視圖時,我會看到包含所有子視圖的照片。如何在不添加子視圖的情況下截取uiview?

let viewPic = UIView() 

      for subview in self.view.subviews { 

       if(subview.tag == 6) { 
        viewPic.addSubview(subview) 
       } 

       if(subview.tag == 8) { 
        viewPic.addSubview(subview) 
       } 
      } 

      let picImage = viewPic.getSnapshotImage() //This is a black screen 

getSnapshotImage

extension UIView { 
    public func getSnapshotImage() -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0) 
     self.drawHierarchy(in: self.bounds, afterScreenUpdates: false) 
     let snapshotItem: UIImage = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 
     return snapshotItem 
    } 
} 
+0

從這個答案參考,它可能會幫助的你[iOS的截圖部分屏幕(http://stackoverflow.com/questions/12687909/ios-screenshot-part-of-the-screen) – iDevAmit

回答

0

首先,你viewPic不設置幀大小,因此默認將是零幀這可能會導致問題。其次,我嘗試在我的示例項目上使用您的getSanpshotImage(),但我總是得到空白圖像。

看一看演示代碼,我可以給你想要的(見截圖)什麼:

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     let viewPic = UIView() 
     viewPic.frame = self.view.frame 

     let view1 = UIView() 
     view1.frame = CGRect(x: 0, y: 0, width: 100, height: 100) 
     view1.backgroundColor = UIColor.red 
     viewPic.addSubview(view1) 

     let view2 = UIView() 
     view2.frame = CGRect(x: 0, y: 200, width: 100, height: 100) 
     view2.backgroundColor = UIColor.blue 
     viewPic.addSubview(view2) 

     let picImage = viewPic.convertToImage() //This is a black screen 
     print(picImage) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

extension UIView { 
    func convertToImage() -> UIImage { 
     let renderer = UIGraphicsImageRenderer(bounds: bounds) 
     return renderer.image { rendererContext in 
      layer.render(in: rendererContext.cgContext) 
     } 
    } 
} 

enter image description here

相關問題