我有一个(动画的) UIView-Hierarchy,我想定期将UIView内容呈现到MTLTexture中以便进一步处理。
我尝试的是继承父UIView的子类,并
override public class var layerClass: Swift.AnyClass {
return CAMetalLayer.self
}但是来自nextDrawable()的纹理是黑色的,并且不显示视图内容。
你知道如何获取包含视图内容的MTLTexture吗?
发布于 2020-05-18 13:00:53
感谢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
}
}https://stackoverflow.com/questions/61724043
复制相似问题