UIView的drawHierarchy vs CALayer的render

来源:互联网 发布:淘宝要求3c认证 编辑:程序博客网 时间:2024/04/29 08:33

项目中有这样的需求:将多个视图进行拼接成为一张图片,进而进行分享。大体思路是将多个视图放在一个父视图中,再将父视图转换成图片。视图转图片的代码:

func convertViewToImage(_ useViewDrawing: Bool = false) -> UIImage? {        var rect = self.frame        if self.isKind(of: UIScrollView.self) {            rect.size = (self as! UIScrollView).contentSize        }        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)        guard let context = UIGraphicsGetCurrentContext() else {return nil}        context.saveGState()        context.translateBy(x: self.center.x, y: self.center.y)        context.concatenate(self.transform)        context.translateBy(x: -self.bounds.size.width * self.layer.anchorPoint.x, y: -self.bounds.size.height * self.layer.anchorPoint.y)        if useViewDrawing && self.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:))) {            // afterScreenUpdates true:包含最近的屏幕更新内容 false:不包含刚加入视图层次但未显示的内容            self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)        } else {            self.layer.render(in: context)        }        context.restoreGState()        let image = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return image    }

几个版本运行没问题,前几天有用户反馈说他分享出来的内容是空的。分析了一下是他的数据过多,拼接成的视图Size(375, 7000),最终self.drawHierarchy处理后得到了空数据,没有得到期望的结果。
经过测试发现:
1,self.drawHierarchy虽然比layer渲染速度快,但是处理超长视图时无法得到其图片,这是需要用Layer的渲染函数来处理。
2,对于地图视图,如果用Layer渲染的方法,得到是黑色图片,必须用UIView的描画函数。

原创粉丝点击