gpt4 book ai didi

ios - 将 UIView 内容渲染到 MTLTexture 中

转载 作者:行者123 更新时间:2023-12-01 16:12:20 25 4
gpt4 key购买 nike

我有一个(动画)UIView-Hierarchy,我想定期将 UIView 内容渲染到 MTLTexture 中以供进一步处理。

我尝试过的是子类化我的父 UIView 和

override public class var layerClass: Swift.AnyClass {
return CAMetalLayer.self
}

但是 nextDrawable() 的纹理是黑色的,不显示 View 内容。

关于如何获取包含 View 内容的 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
}
}

关于ios - 将 UIView 内容渲染到 MTLTexture 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61724043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com