1

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?

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31

1 Answers1

2

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.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • got it.It worked.thanks for the tip Ken.Btw when I replace portion of pixels in the texture, color values are changed from actual values of that particular set of pixels.Do you know any possible reason for this kind of behavior – Kasun Palihakkara Jul 04 '18 at 12:20
  • Not sure. Depends on what you're doing exactly and the pixel format of the data you're supplying. Probably best to open a new question with those details, what you expected, and what you actually got. – Ken Thomases Jul 04 '18 at 14:29
  • Thanks ken.I figured it out lately.Yes indeed it's because of pixel format. Instead of pixelFormat: .bgra8Unorm in MTLTextureDescriptor i have accidently added .argb8Unorm which causes to unexpected behaviour. – Kasun Palihakkara Jul 05 '18 at 04:34