当有硬件加速内容(一些在 iframe 内运行的特定赌场游戏)时,我在截取WKWebview内容的屏幕截图时遇到了严重的问题。到目前为止,我使用了每个人建议的标准截屏方式:
UIGraphicsBeginImageContextWithOptions(containerView.frame.size, true, 0.0)
containerView.layer.render(in: UIGraphicsGetCurrentContext()!)
//This line helps to fix view rendering for taking screenshot on older iOS devices
containerView.drawHierarchy(in: containerView.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
Run Code Online (Sandbox Code Playgroud)
这种方法非常有效,直到我在我的 WKWebview 中获得了一些由 GPU 呈现的内容。GPU 渲染的内容在屏幕截图上显示为黑色。我尝试了这种方法可能的所有技巧,但没有任何帮助。甚至 XCode 视图层次结构调试器也无法显示硬件加速的内容。因此,类似于Android,我需要另一种截屏方式。我已经通过开始记录屏幕上发生的所有事情并在获得第一张图像后停止屏幕记录来解决 Android 上的类似问题。
我经历了许多 Stack Overflow 问题和解决方案,但它们大部分都在 Obj-C 中(我完全不擅长),已经过时或不够具体,无法满足我的需求。
现在我发现,我可以使用glReadPixels从 OpenGL 中读取像素(如果我的内容是硬件加速的,那么我可以从显卡读取这些像素是有意义的,对吗??)
到目前为止,我已经设法创建了一个 Swift 代码段,它执行类似renderBuffer -> frameBuffer -> glReadPixels -> image 的操作
let width = Int(containerView.frame.size.width)
let height = Int(containerView.frame.size.height)
//BeginImageContext code …Run Code Online (Sandbox Code Playgroud)