Swift: Cropping a Screenshot without TabBar and NavigationBar

前端 未结 5 822
臣服心动
臣服心动 2021-01-05 14:43

I have a screenshot of the entire screen, screenshot, generated using the following:

let layer = UIApplication.sharedApplication().keyWindow!.l         


        
5条回答
  •  时光说笑
    2021-01-05 15:20

    You have two options here: First, you can take the screenshot using UIApplication.sharedApplication().keyWindow then we will have this:

        UIGraphicsBeginImageContext(UIApplication.sharedApplication().keyWindow!.bounds.size)
        UIApplication.sharedApplication().keyWindow!.layer.renderInContext(UIGraphicsGetCurrentContext())
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    

    So, you will have to crop the image like this:

        let yPosition = self.navigationController!.navigationBar.frame.height + UIApplication.sharedApplication().statusBarFrame.size.height
        let crop = CGRectMake(0, yPosition,
                self.view.bounds.width, 
                self.view.bounds.height)
        let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
        let image: UIImage = UIImage(CGImage: cgImage)!
    

    The second option is to take the screenshot directly of your view, like this:

        UIGraphicsBeginImageContext(self.view!.bounds.size)
        self.view!.layer.renderInContext(UIGraphicsGetCurrentContext())
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    

    In this case, you don't need to crop the navigationBar.

    This is a sample code at github https://github.com/gazolla/crop

提交回复
热议问题