Screenshot on swift programmatically

前端 未结 1 1900
梦如初夏
梦如初夏 2020-12-12 05:11

i\'m trying to take a screenshot of the whole view when i press a button in swift. The problem is that, when i take the screenshot, some parts are cut off, like the top...

相关标签:
1条回答
  • 2020-12-12 05:45

    If you have some sort of Objective-C knowledge then here is the answer that you want.

    Open this Link and follow the last answer which iterates through all the view hierarchy and And have line by line comments to fully understand the code.

    The Image is finally converted into both NSData and UIImage. If you are still confuse then i can convert it into swift but first try it by your self.

    Here is the Swift code of that Answer.

    func screenshot() -> UIImage {
        let imageSize = UIScreen.main.bounds.size as CGSize;
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        let context = UIGraphicsGetCurrentContext()
        for obj : AnyObject in UIApplication.shared.windows {
            if let window = obj as? UIWindow {
                if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
                                    // so we must first apply the layer's geometry to the graphics context
                                    context!.saveGState();
                                    // Center the context around the window's anchor point
                                    context!.translateBy(x: window.center.x, y: window.center
                                        .y);
                                    // Apply the window's transform about the anchor point
                                    context!.concatenate(window.transform);
                                    // Offset by the portion of the bounds left of and above the anchor point
                    context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x,
                                         y: -window.bounds.size.height * window.layer.anchorPoint.y);
    
                                    // Render the layer hierarchy to the current context
                                    window.layer.render(in: context!)
    
                                    // Restore the context
                                    context!.restoreGState();
                }
            }
        }
        let image = UIGraphicsGetImageFromCurrentImageContext();
        return image!
    }
    
    0 讨论(0)
提交回复
热议问题