uiimage to metal in swift

Converting a UIImage to Metal texture in Swift involves a few steps. First, we create a MTLTextureDescriptor object that describes the texture we want to create. Then, we load the image from the UIImage into a CGImage object. Lastly, we use Core Graphics to copy the pixel data from the CGImage into the Metal texture.

main.swift
import MetalKit

func uiImageToMetalTexture(image: UIImage, device: MTLDevice) -> MTLTexture? {
    guard let cgImage = image.cgImage else {
        return nil
    }
    
    // Create a texture descriptor that describes the texture we want to create
    let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(
        pixelFormat: .rgba8Unorm,
        width: cgImage.width,
        height: cgImage.height,
        mipmapped: false)
    
    // Create a Metal texture from the texture descriptor
    guard let texture = device.makeTexture(descriptor: textureDescriptor) else {
        return nil
    }
    
    // Copy the pixel data into the Metal texture using Core Graphics
    let bytesPerRow = cgImage.width * 4
    let region = MTLRegionMake2D(0, 0, cgImage.width, cgImage.height)
    guard let context = CGContext(
        data: texture.buffer?.contents(),
        width: cgImage.width,
        height: cgImage.height,
        bitsPerComponent: 8,
        bytesPerRow: bytesPerRow,
        space: CGColorSpaceCreateDeviceRGB(),
        bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
    else {
        return nil
    }
    
    context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
    
    return texture
}
1273 chars
39 lines

Note that we use the contents() method of the MTLBuffer object returned by device.makeTexture(descripor:) to get a UnsafeMutableRawPointer to the texture's buffer. This allows us to copy the pixel data into the Metal texture. Also note that this function assumes that the UIImage is in the RGBA8 format. If you're working with images in a different format, you'll need to modify the pixel format in the texture descriptor accordingly.

gistlibby LogSnag