以编程方式在swift上的屏幕截图

时间:2016-12-23 22:53:51

标签: ios swift

当我在swift中按下按钮时,我正试图截取整个视图的截图。问题在于,当我拍摄截图时,有些部分会被切断,就像顶部...

enter image description here

其他被切断的部分是我在屏幕底部的容器视图。它包含一个开关,一个文本域和一个按钮。这是我用来截取屏幕截图的代码......

func screenShotMethod() {
    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

    layer.render(in: UIGraphicsGetCurrentContext()!)
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil)
}

这是我用来创建容器视图的代码......

lazy var inputContainerView: UIView = {

    let containerView = UIView()
    containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)
    containerView.backgroundColor = UIColor.white
    //Other things...

override var inputAccessoryView: UIView? {
    get {
        return inputContainerView
    }
}

override var canBecomeFirstResponder : Bool {
    return true
}

这就是压轴图像的样子...... enter image description here

那么我该怎么做才能解决它? 谢谢!

1 个答案:

答案 0 :(得分:4)

如果你有某种Objective-C知识,那么这就是你想要的答案。

打开此Link并按照最后一个回答所有视图层次结构的答案,然后逐行注释以完全理解代码。

图片最终转换为NSDataUIImage。 如果你仍然感到困惑,那么我可以将它转换为快速但首先尝试自己。

这是答案的Swift代码。

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!
}