在Swift中使用renderInContext在屏幕上显示所选视图时捕获问题 [英] Issue capturing selected views as they appear on screen with renderInContext in Swift

查看:109
本文介绍了在Swift中使用renderInContext在屏幕上显示所选视图时捕获问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的故事板上有三个视图,分别是viewAviewBviewC.

I have three views on my storyboard, viewA, viewB, viewC.

我正在尝试捕获当前显示在屏幕上的两个视图,分别是 viewB viewC .

I’m trying to screen capture only two views as they appear on screen in their current place, viewB and viewC.

问题在于,当我渲染它们时,捕获的结果图像显示viewBviewC在不正确的位置,视图的位置向左上方移动(0、0),请参见图像.

The trouble is, when I render them, the resulting image captured shows viewB and viewC in incorrect locations, the position of the views change moving top left (0, 0), see image.

如何纠正下面的代码,以便可以使用下面的renderInContext实现完全捕获视图viewBviewC的位置?

How can I correct the code below so that I can capture the views viewB and viewC exactly as they are positioned on the view using the renderInContext implementation below?

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

推荐答案

来自renderInContext:的文档:

在图层的坐标空间中渲染.

Renders in the coordinate space of the layer.

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

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

要解决此问题,您需要在调用renderInContext:之前按视图的原点翻译图形上下文.

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()

这篇关于在Swift中使用renderInContext在屏幕上显示所选视图时捕获问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆