下载为PNG时,向MTLTexture发送UIImage

时间:2016-06-01 01:38:28

标签: ios objective-c uiimage metal

我的用例是用户在手机上拍摄自己的照片,然后将其作为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 个答案:

答案 0 :(得分:6)

Metal坐标相反。但是,您现在可以使用MTKTextureLoader加载纹理的方法更加简单:

import MetalKit

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

这将使用位于texture的图片为您创建一个新的filePath,并使用适当的坐标。如果您不想使用NSURL,那么您还拥有newTextureWithDatanewTextureWithCGImage选项。