我有一个(动画)UIView-Hierarchy,我想定期将 UIView 内容渲染到 MTLTexture 中以进行进一步处理。
我尝试过的是子类化我的父 UIView 和
override public class var layerClass: Swift.AnyClass {
return CAMetalLayer.self
}
但 nextDrawable() 的纹理是黑色的,不显示视图内容。
有什么想法如何获取包含视图内容的 MTLTexture 吗?
谢谢马蒂斯·霍勒曼斯 https://stackoverflow.com/users/7501629/matthijs-hollemans他用一些代码为我指明了正确的方向,我想出了以下 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)