我有一个(动画的)UIView层次结构,我想定期将UIView内容呈现到MTLTexture中以进行进一步处理。
我尝试过的是将父UIView子类化,并且
override public class var layerClass: Swift.AnyClass {
return CAMetalLayer.self
}
但是nextDrawable()中的纹理为黑色,不显示视图内容。
任何想法如何获取包含视图内容的MTLTexture?
由于Matthijs Hollemanns用一些代码将我引向正确的方向,我想到了以下UIView扩展,该扩展在iPhone8plus上以每帧约12毫秒的速度完成了工作,从而获得了全屏分辨率。
extension UIView {
func takeTextureSnapshot(device: MTLDevice) -> MTLTexture? {
let width = Int(bounds.width)
let height = Int(bounds.height)
if let context = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue),
let data = context.data {
layer.render(in: context)
let desc = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
width: width,
height: height,
mipmapped: false)
if let texture = device.makeTexture(descriptor: desc) {
texture.replace(region: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0,
withBytes: data,
bytesPerRow: context.bytesPerRow)
return texture
}
}
return nil
}
}