UIImage转换为MTLTexture时,下载为PNG格式。

4
我的使用场景是用户在手机上拍照并将其作为JPEG上传到图像托管服务。其他用户可以下载该图像,并将该图像映射到金属纹理中以供游戏使用。
我的问题是,如果我下载该图像并简单地在UIImageView中显示它,它看起来很正常,但当我将下载的图像转换为金属纹理时,它会被镜像和顺时针旋转90度。我知道图像被镜像是由于金属具有不同的坐标系,但我不明白旋转问题。当我打印传递给我的函数的图像的详细信息时,它具有与正确显示的UIImageView相同的方向详细信息,因此我不知道问题出在哪里。附上提供我的MTLTexture的函数。
- (id<MTLTexture>) createTextureFromImage:(UIImage*) image device:(id<MTLDevice>) device
{
  image  =[UIImage imageWithCGImage:[image CGImage]
                   scale:[image scale]
                   orientation: UIImageOrientationLeft];

  NSLog(@"orientation and size and stuff %ld %f %f", (long)image.imageOrientation, image.size.width, image.size.height);

  CGImageRef imageRef = image.CGImage;

  size_t width = self.view.frame.size.width;
  size_t height = self.view.frame.size.height;

  size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
  size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);

  CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);

  CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);

  //  NSLog(@"%@ %u", colorSpace, alphaInfo);

  CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | alphaInfo;
  //    NSLog(@"bitmap info %u", bitmapInfo);


  CGContextRef context = CGBitmapContextCreate( NULL, width, height, bitsPerComponent, (bitsPerPixel / 8) * width, colorSpace, bitmapInfo);

  if( !context )
  {
    NSLog(@"Failed to load image, probably an unsupported texture type");
    return nil;
  }




  CGContextDrawImage( context, CGRectMake( 0, 0, width, height ), image.CGImage);


  MTLPixelFormat format = MTLPixelFormatRGBA8Unorm;

  MTLTextureDescriptor *texDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format
                                                                                     width:width
                                                                                    height:height
                                                                                 mipmapped:NO];
  id<MTLTexture> texture = [device newTextureWithDescriptor:texDesc];

  [texture replaceRegion:MTLRegionMake2D(0, 0, width, height)
             mipmapLevel:0
               withBytes:CGBitmapContextGetData(context)
             bytesPerRow:4 * width];

  return texture;
}
1个回答

10
Metal 中,坐标被颠倒了。但是,现在你有了一种更简单的方法来使用 MTKTextureLoader 来加载纹理:
import MetalKit

let textureLoader = MTKTextureLoader(device: device)
let texture: MTLTexture = textureLoader.newTextureWithContentsOfURL(filePath, options: nil)

使用位于 filePath 的图像,可以为您创建具有适当坐标的新 texture。如果您不想使用 NSURL,您还可以使用 newTextureWithDatanewTextureWithCGImage 选项。


天啊!非常感谢您。您能指导我找到文档或您学习那个的地方吗? - stktrc
2
当然可以。这里是MetalKit纹理加载器的文档和一些示例代码 - gpu3d

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接