Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/122.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中使用RenderContext捕获屏幕上显示的选定视图时出现问题_Ios_Swift_Uigraphicscontext - Fatal编程技术网

Ios 在Swift中使用RenderContext捕获屏幕上显示的选定视图时出现问题

Ios 在Swift中使用RenderContext捕获屏幕上显示的选定视图时出现问题,ios,swift,uigraphicscontext,Ios,Swift,Uigraphicscontext,我的故事板上有三个视图,viewA,viewB,viewC 我试图只截取屏幕上当前位置出现的两个视图,viewB和viewC 问题是,当我渲染它们时,捕获的结果图像在不正确的位置显示viewB和viewC,视图的位置会改变,移动到左上角(0,0),请参见图像 如何更正下面的代码,以便使用下面的renderInContext实现捕获视图viewB和viewC,使其与视图上的位置完全一致 UIGraphicsBeginImageContextWithOptions(self.view.frame.s

我的故事板上有三个视图,
viewA
viewB
viewC

我试图只截取屏幕上当前位置出现的两个视图,
viewB
viewC

问题是,当我渲染它们时,捕获的结果图像在不正确的位置显示
viewB
viewC
,视图的位置会改变,移动到左上角(0,0),请参见图像

如何更正下面的代码,以便使用下面的
renderInContext
实现捕获视图
viewB
viewC
,使其与视图上的位置完全一致

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0)
self.viewB.layer.renderInContext(UIGraphicsGetCurrentContext()!)
self.viewC.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

来自
渲染上下文的文档:

在层的坐标空间中渲染

每个视图的图层的原点为0,0,因此它们都显示在左上角

要解决此问题,您需要在调用
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()

感谢您的回复@rmaddy。我如何具体地“翻译图形上下文”呢?请参阅我的更新。我相信这是正确的。它没有经过测试。谢谢@rmaddy。我已经测试过了,效果很好。我必须将
-self.viewC
更改为
self.viewC
删除
-
,它才能工作。后来我添加了一个新的视图,由于某些原因,我很难捕捉到它,它从未显示,我怀疑它可能与自动约束有关,但不确定我正在调查的原因。这个答案+正是所需要的。爱如此:-)