如何使用扩展市场保存裁剪后的uiview屏幕截图

时间:2019-10-14 19:37:59

标签: swift uiview uiviewcontroller uiimage extension-methods

我的扩展方法现在在视图控制器内部截取整个uiview的屏幕截图。我想使用相同的功能来做相同的事情,只是占用uiview的确切区域而不是整个视图。具体来说,我想捕获x:0,y:0,长度200,高度200,

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

1 个答案:

答案 0 :(得分:1)

怎么样:

if (active) {
    if (delay) window.clearTimeout(delay)
    delay = setTimeout(function() {
        console.log("move")
        window.scrollTo(0,document.body.scrollHeight);
    }, 50);
}

这使它更具可重用性,但是您可以根据需要将其更改为硬编码值。

extension UIView { func screenshot(for rect: CGRect) -> UIImage { return UIGraphicsImageRenderer(bounds: rect).image { _ in drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true) } } }