OPenGL ES纹理翻转解决方案

2019-06-12  本文已影响0人  zhongxiaoyue

纹理翻转

在使用OpenGL函数加载纹理到图形时,经常遇到纹理上下颠倒的问题。原因是因为OpenGL要求纹理坐标原点在图片左下角,而图片信息中的原点一般都在左上角,一行行渲染下来的,就会导致整个图片上下颠倒了!

解决方案

//1. rotate等于shaderv.vsh中的uniform属性,rotateMatrix
GLuint rotate = glGetUniformLocation(self.myPrograme, "rotateMatrix");

//2.获取渲旋转的弧度
float radians = 180 * 3.14159f / 180.0f;

//3.求得弧度对于的sin\cos值
float s = sin(radians);
float c = cos(radians);

//4.Z轴旋转矩阵
GLfloat zRotation[16] = {
    c,-s,0,0,
    s,c,0,0,
    0,0,1,0,
    0,0,0,1
};

//5.设置旋转矩阵
glUniformMatrix4fv(rotate, 1, GL_FALSE, zRotation);
//1、将 UIImage 转换为 CGImageRef
CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;

//判断图片是否获取成功
if (!spriteImage) {
    NSLog(@"Failed to load image %@", fileName);
    exit(1);
}

//2、读取图片的大小,宽和高
size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);

//3.获取图片字节数 宽*高*4(RGBA)
GLubyte * spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));

//4.创建上下文
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4,CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);


//5、在CGContextRef上--> 将图片绘制出来
CGRect rect = CGRectMake(0, 0, width, height);

//6.翻转图片
CGContextTranslateCTM(spriteContext, 0, rect.size.height);
CGContextScaleCTM(spriteContext, 1.0, -1.0);

//7.绘制
CGContextDrawImage(spriteContext, rect, spriteImage);

//8、画图完毕就释放上下文
CGContextRelease(spriteContext);

//9、绑定纹理到默认的纹理ID
glBindTexture(GL_TEXTURE_2D, 0);
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;

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

void main()
{
    varyTextCoord = vec2(textCoordinate.x,1.0-textCoordinate.y);
    gl_Position = position;
}
//    修改纹理坐标前数据
//    GLfloat attrArr[] =
//    {
//        0.5f, -0.5f, -1.0f,     1.0f, 0.0f,
//        -0.5f, 0.5f, -1.0f,     0.0f, 1.0f,
//        -0.5f, -0.5f, -1.0f,    0.0f, 0.0f,
//
//        0.5f, 0.5f, -1.0f,      1.0f, 1.0f,
//        -0.5f, 0.5f, -1.0f,     0.0f, 1.0f,
//        0.5f, -0.5f, -1.0f,     1.0f, 0.0f,
//    };
    
    // 修改纹理坐标后数据
    GLfloat attrArr[] =
    {
        0.5f, -0.5f, -1.0f,     1.0f, 1.0f,
        -0.5f, 0.5f, -1.0f,     0.0f, 0.0f,
        -0.5f, -0.5f, -1.0f,    0.0f, 1.0f,
        
        0.5f, 0.5f, -1.0f,      1.0f, 0.0f,
        -0.5f, 0.5f, -1.0f,     0.0f, 0.0f,
        0.5f, -0.5f, -1.0f,     1.0f, 1.0f,
    };
上一篇 下一篇

猜你喜欢

热点阅读