在UIImage到纹理转换中,纹理垂直翻转

时间:2011-11-14 23:36:11

标签: ios ios4 opengl-es-2.0

我正在尝试将UIImage读入iOS平台上的纹理。我发现StackOverflow上的代码片段可以解决问题,但问题是当我显示纹理时它显示为镜像颠倒。

int numComponents = 4;

UIImage* image = [UIImage imageNamed:@"Test.png"];
CGImageRef imageRef = [image CGImage];
int width = CGImageGetWidth(imageRef);
int height = CGImageGetHeight(imageRef);

//Allocate texture data
GLubyte* textureData = (GLubyte *)malloc(width * height * numComponents);    

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(textureData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

//texture setup
GLuint textureID;    
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &textureID);

glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureDataMirrored);   

我还尝试使用以下行(在读取数据之前)镜像UIImage,但它也不起作用。实际上没有任何影响。

image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationUpMirrored]; 

请告诉我这里我做错了什么。谢谢。

1 个答案:

答案 0 :(得分:5)

这两行解决了问题

CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0,height);
CGContextConcatCTM(context, flipVertical);