【问题标题】:Render UIView contents into MTLTexture将 UIView 内容渲染到 MTLTexture
【发布时间】:2020-08-26 15:50:27
【问题描述】:

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

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

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

但是来自 nextDrawable() 的纹理是黑色的并且不显示视图内容。

知道如何获取包含视图内容的 MTLTexture 吗?

【问题讨论】:

标签: ios uikit rendering textures metal


【解决方案1】:

感谢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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多