2

I am trying to load an asset image in Metal like so:

let textureLoader = MTKTextureLoader(device: context.device)
do{
    let image = UIImage(named: name)
    try texture = textureLoader.newTextureWithCGImage(image!.CGImage!, options: [:])
}catch let error{
    print("Failed to create texture, error \(error)")
}

I am able to display the image but the colors are permuted, as if the file contains RGB data but it is being interpreted as BGR data. I know the default color space for a Metal layer is BGRA8Unorm but I don't know how to force the image to be loaded in that format.

user16217248
  • 3,119
  • 19
  • 19
  • 37
gloo
  • 2,490
  • 3
  • 22
  • 38

1 Answers1

0

You should use the designated class method on MTKTextureLoader to create a new MTLTexture from an URL:

let device = MTLCreateSystemDefaultDevice()!
let loader = MTKTextureLoader(device: device)
let url = NSBundle.mainBundle().URLForResource("pic", withExtension: "jpg")!
let texture = try! loader.newTextureWithContentsOfURL(url, options: nil)
Silvan Mosberger
  • 1,786
  • 14
  • 19
  • This was actually the very first thing I tried but I cannot get it to find the image this way. I get the error `fatal error: unexpectedly found nil while unwrapping an Optional value`. My image is located in `Assets.xcassets`. How do I properly specify a path to that folder? – gloo Aug 15 '16 at 16:49
  • 1
    There is currently no easy way to get the URL of an asset in an asset catalog. If you're using asset catalogs, you should use one of the [methods that knows how to load named assets](https://developer.apple.com/reference/metalkit/mtktextureloader/1645855-newtexture). – warrenm Aug 15 '16 at 17:20
  • I don't think that method has been implemented yet. My instance of `MTKTextureLoader` does not have that function. I guess I will try storing the image outside the assets folder – gloo Aug 15 '16 at 17:29
  • 1
    To get URLs for my assets I just include the asset folder name in the file name, like this: let url = NSBundle.mainBundle().URLForResource("Assets.xcassets/pic", withExtension: "jpg") – John Stephen Aug 15 '17 at 16:35