如何将bgra8Unorm iOS-Metal纹理转换为rgba8Unorm纹理?

时间:2017-12-28 13:51:21

标签: ios swift textures gpu metal

我正在使用iOS 11,XCode 9和Metal 2.我有MTLTexture像素格式bgra8Unorm。我无法更改此像素格式,因为根据pixelFormat documentation

  

金属图层的像素格式必须为bgra8Unorm,bgra8Unorm_srgb,rgba16Float,BGRA10_XR或bgra10_XR_sRGB。

其他像素格式不适合我的应用程序。

现在我想从纹理中创建一个UIImage。我可以通过从纹理(doc)中提取像素字节来实现:

getBytes(_:bytesPerRow:bytesPerImage:from:mipmapLevel:slice:)

我正在处理这些字节以获得UIImage

func getUIImageForRGBAData(data: Data) -> UIImage? {
    let d = (data as NSData)

    let width = GlobalConfiguration.textureWidth
    let height = GlobalConfiguration.textureHeight
    let rowBytes = width * 4
    let size = rowBytes * height

    let pointer = malloc(size)
    memcpy(pointer, d.bytes, d.length)

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let context = CGContext(data: pointer, width: width, height: height, bitsPerComponent: 8, bytesPerRow: rowBytes, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

    let imgRef = context.makeImage()
    let image = UIImage(cgImage: imgRef!)
    return image
}

但是,CGContext假设像素采用rgba8格式。例如,红色纹理像素在最终的UIImage中是蓝色的。有没有办法在这个过程中更改pixelFormat以获得正确的颜色?

1 个答案:

答案 0 :(得分:4)

此函数会将.bgra8Unorm纹理的字节转换为RGBA顺序,并从数据中创建UIImage

func makeImage(from texture: MTLTexture) -> UIImage? {
    let width = texture.width
    let height = texture.height
    let bytesPerRow = width * 4

    let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
    defer {
        data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
    }

    let region = MTLRegionMake2D(0, 0, width, height)
    texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)

    var buffer = vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: bytesPerRow)

    let map: [UInt8] = [2, 1, 0, 3]
    vImagePermuteChannels_ARGB8888(&buffer, &buffer, map, 0)

    guard let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear) else { return nil }
    guard let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow,
                                  space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
    guard let cgImage = context.makeImage() else { return nil }

    return UIImage(cgImage: cgImage)
}

警告:此功能非常昂贵。每帧从Metal纹理创建一个图像几乎不是你想要做的。