首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用扩展市场保存裁剪的uiview屏幕截图

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

Stack Overflow用户
提问于 2019-10-15 03:38:00
回答 1查看 33关注 0票数 0

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

代码语言:javascript
复制
    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!
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-15 05:02:38

这样如何:

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

这使得它更具可重用性,但如果您愿意,您可以将其更改为硬编码值。

let image = self.view.screenshot(for: CGRect(x: 0, y: 0, width: 200, height: 200))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58383080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档