首页 > 解决方案 > 使用全色深度 MTLTextureDescriptor 创建 MTLTexture

问题描述

我有以下功能来创建 MTL 纹理;

let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = Int(4)
let bitsPerComponent = Int(8)
let bitsPerPixel:Int = 32
var textureSizeX:Int = 1200
var textureSizeY:Int = 1200

func setupTexture() {

    var rawData0 = [UInt8](repeating: 0, count: Int(textureSizeX) * Int(textureSizeY) * 4)

    let bytesPerRow = 4 * Int(textureSizeX)
    let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue

    let context = CGContext(data: &rawData0, width: Int(textureSizeX), height: Int(textureSizeY), bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: rgbColorSpace, bitmapInfo: bitmapInfo)!
    context.setFillColor(UIColor.black.cgColor)
    context.fill(CGRect(x: 0, y: 0, width: CGFloat(textureSizeX), height: CGFloat(textureSizeY)))

    let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: MTLPixelFormat.rgba8Unorm, width: Int(textureSizeX), height: Int(textureSizeY), mipmapped: false)

    textureDescriptor.usage = MTLTextureUsage(rawValue: MTLTextureUsage.renderTarget.rawValue | MTLTextureUsage.shaderRead.rawValue)

    let textureA = device.makeTexture(descriptor: textureDescriptor)

    let region = MTLRegionMake2D(0, 0, Int(textureSizeX), Int(textureSizeY))
    textureA?.replace(region: region, mipmapLevel: 0, withBytes: &rawData0, bytesPerRow: Int(bytesPerRow))

    offscreenTexture = textureA

}

如何更改此功能以生成可以处理完整 32 位颜色深度的纹理?这种纹理产生的颜色对于我的需要来说太有限了。

进一步说明:

我问这个的原因是因为以下。

我正在使用应用于 SCNMaterial 的 SKRenderer 将着色器(您在下面看到的橙色发光点)渲染到纹理。

当我在 SpriteKit 场景中正常渲染着色器并将其用作 SCNMaterial 的纹理时,我得到了我想要的丰富橙色外观,如 TOP 图像中所示。

但是,当我使用 SKRenderer 方法处理图像时,结果看起来像 BOTTOM 图像,其中颜色看起来更黄,被稀释并且不那么丰富。

在此处输入图像描述

在此处输入图像描述

我把这归结为我在创建 MTLTexture 时没有足够的色彩准确度。我对纹理创建的了解不够,不知道我可能做错了什么,但我相信有一种方法可以增加颜色的丰富度/准确性。如何??

标签: iosswiftsprite-kitscenekitmetal

解决方案


推荐阅读