stk*_*trc 4 objective-c uiimage ios 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;
}
Run Code Online (Sandbox Code Playgroud)
在Metal坐标中是相反的.但是,您现在有一种更简单的方法来加载纹理MTKTextureLoader:
import MetalKit
let textureLoader = MTKTextureLoader(device: device)
let texture: MTLTexture = textureLoader.newTextureWithContentsOfURL(filePath, options: nil)
Run Code Online (Sandbox Code Playgroud)
这将texture使用位于的图像为您创建一个新的适当坐标filePath.如果你不想使用NSURL你也有newTextureWithData和newTextureWithCGImage选项.