Skip to content

Instantly share code, notes, and snippets.

@kunofellasleep
Last active October 6, 2018 04:05
Show Gist options
  • Save kunofellasleep/b333f42651e13d7c7e4f1a5591eb0b77 to your computer and use it in GitHub Desktop.
Save kunofellasleep/b333f42651e13d7c7e4f1a5591eb0b77 to your computer and use it in GitHub Desktop.
func mtlTexture(from image: UIImage) -> MTLTexture {
//CGImage変換時に向きがおかしくならないように
UIGraphicsBeginImageContext(image.size);
image.draw(in: CGRect(x:0, y:0, width:image.size.width, height:image.size.height))
let orientationImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//CGImageに変換
guard let cgImage = orientationImage?.cgImage else {
fatalError("Can't open image \(image)")
}
//MTKTextureLoaderを使用してCGImageをMTLTextureに変換
let textureLoader = MTKTextureLoader(device: self.device)
do {
let tex = try textureLoader.newTexture(cgImage: cgImage, options: nil)
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: tex.pixelFormat, width: tex.width, height: tex.height, mipmapped: false)
textureDescriptor.usage = [.shaderRead, .shaderWrite]
return tex
}
catch {
fatalError("Can't load texture")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment