Search code examples
swiftmetalmetalkitmtlbuffer

access particular set of pixels MTLTexture in metal


I created an MTLTexture using UIImage data as follows.

var texture = metalView.currentDrawable!.texture
let uiImg = createImageFromCurrentDrawable()
            
guard let device = metalView.device else {
    fatalError("Device not created. Run on a physical device")
}
let textureLoader = MTKTextureLoader(device: device)
let imageData: NSData = UIImagePNGRepresentation(uiImg)! as NSData
texture = try! textureLoader.newTexture(data: imageData as Data, options: [MTKTextureLoader.Option.allocateMipmaps: (false as NSNumber)])
            

what I need to do is change pixels color in MTLTexture. Not all of them. So, is it possible to access a particular set of pixels in MTLtexture and write into it in Metal?


Solution

  • Yes, as a look at the MTLTexture documentation would have shown you. You can use one of the getBytes() methods to copy a region of texture data out to a buffer, and one of the replace() methods to replace a region of the texture's pixel with data from a buffer you supply.