十、iOS OpenGL ES纹理翻转解决策略

1. GLKTextureLoader载入纹理时

载入时options设置 GLKTextureLoaderOriginBottomLeft

NSDictionary *options = @{GLKTextureLoaderOriginBottomLeft : @(YES)};
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:options error:nil];

2. 解压图片时,将图片翻转

CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;

size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
GLubyte *spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));

CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
  
CGRect rect = CGRectMake(0, 0, width, height);
CGContextTranslateCTM(spriteContext, 0, rect.size.height);
CGContextScaleCTM(spriteContext, 1.0, -1.0);
CGContextDrawImage(spriteContext, rect, spriteImage); 

CGContextRelease(spriteContext);
glBindTexture(GL_TEXTURE_2D, 0);

3. 设置旋转矩阵,shader中旋转顶点,不翻转纹理

GLuint rotate = glGetUniformLocation(self.program, "rotateMatrix");
float radians = M_PI;
float sinR = sin(radians);
float cosR = cos(radians);
GLfloat zRotation[16] = {
    cosR, -sinR, 0, 0,
    sinR, cosR, 0, 0,
    0, 0, 1.0, 0,
    0.0, 0, 0, 1.0
};
glUniformMatrix4fv(rotate, 1, GL_FALSE, (GLfloat *)&zRotation[0]);

4. 设置翻转的纹理坐标映射关系

GLfloat datas[] =
{
    0.5f, -0.5f, 0.0f,   1.0f, 1.0f, //右下
    -0.5f, 0.5f, 0.0f,   0.0f, 0.0f, // 左上
    -0.5f, -0.5f, 0.0f,  0.0f, 1.0f, // 左下
    0.5f, 0.5f, 0.0f,    1.0f, 0.0f, // 右上
    -0.5f, 0.5f, 0.0f,   0.0f, 0.0f, // 左上
    0.5f, -0.5f, 0.0f,   1.0f, 1.0f, // 右下
};

5. 修改顶点着色器的纹理坐标

attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;
void main()
{
    varyTextCoord = vec2(textCoordinate.x, 1.0-textCoordinate.y);
    gl_Position = position;
}

6. 修改顶点着色器的纹理坐标

varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main()
{
    lowp coord = vec2(varyTextCoord.x, 1.0-varyTextCoord.y);
    gl_FragColor = texture2D(colorMap, coord);
}

你可能感兴趣的:(十、iOS OpenGL ES纹理翻转解决策略)