Issue capturing selected views as they appear on screen with renderInContext in Swift

╄→尐↘猪︶ㄣ 提交于 2019-12-06 00:19:06

From the docs for renderInContext::

Renders in the coordinate space of the layer.

Each view's layer has an origin of 0,0 so they each appear in the upper-left corner.

To fix this you need to translate the graphics context by the view's origin before calling renderInContext:.

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0)
let ctx = UIGraphicsGetCurrentContext()

CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, self.viewB.frame.origin.x, self.viewB.frame.origin.y)
self.viewB.layer.renderInContext(UIGraphicsGetCurrentContext()!)
CGContextRestoreGState(ctx)

CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, self.viewC.frame.origin.x, self.viewC.frame.origin.y)
self.viewC.layer.renderInContext(UIGraphicsGetCurrentContext()!)
CGContextRestoreGState(ctx)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!