How to take screenshot of a UIView in swift?

后端 未结 6 1126
心在旅途
心在旅途 2020-12-07 21:03

I have a UIView named overView:

overView.frame = CGRectMake(self.view.frame.width/25, self.view.frame.height/25, self.view.frame.width/1.3, self.view.frame.h         


        
6条回答
  •  生来不讨喜
    2020-12-07 21:38

    For drawing of one view, just use this:

        // Begin context
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)
    
        // Draw view in that context
        drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
    
        // And finally, get image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    

    If you want to use it multiple times, probably extension would do the job:

    //Swift4

    extension UIView {
    
        func takeScreenshot() -> UIImage {
    
            // Begin context
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
    
            // Draw view in that context
            drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    
            // And finally, get image
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            if (image != nil)
            {
                return image!
            }
            return UIImage()
        }
    }
    

    //Old Swift

    extension UIView {
    
        func takeScreenshot() -> UIImage {
    
            // Begin context
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale)
    
            // Draw view in that context
            drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
    
            // And finally, get image
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return image
        }
    }
    

    To explain what those parameters do:

    UIGraphicsBeginImageContextWithOptions() creates a temporary rendering context into which the original is drawn. The first argument, size, is the target size of the scaled image. The second argument, isOpaque is used to determine whether an alpha channel is rendered. Setting this to false for images without transparency (i.e. an alpha channel) may result in an image with a pink hue. The third argument scale is the display scale factor. When set to 0.0, the scale factor of the main screen is used, which for Retina displays is 2.0 or higher (3.0 on the iPhone 6 Plus).

    More about it here http://nshipster.com/image-resizing/

    As for the draw call, Apple Docs explains it to detail here and here

提交回复
热议问题