前沿
OpenGL要求y轴0.0坐标是在图片的底部的,但是图片的y轴0.0坐标通常在顶部,所以按照一一对应的话,图片会发生倒置的问题
我们经过修改后要求达到的效果是下面的
顶点着色器代码
attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;
void main()
{
varyTextCoord = textCoordinate;
gl_Position = position;
}
片元着色器代码
precision highp float;
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main()
{
gl_FragColor = texture2D(colorMap,varyTextCoord);
}
纹理和顶点坐标对应修改
GLfloat attrArr[] =
{
-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, 0.0f,0.0f,
-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, 1.0f,0.0f,
};
顶点坐标和纹理对应关系
A->Aa B->Bb C->Cc D->Dd
修改顶点着色器
attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;
void main()
{
varyTextCoord = vec2(textCoordinate.x,1.0-textCoordinate.y);
gl_Position = position;
}
修改片元着色器代码
precision highp float;
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main()
{
lowp vec2 tempCoord = vec2(varyTextCoord.x,1.0-varyTextCoord.y);
gl_FragColor = texture2D(colorMap,tempCoord);
}
解压图片时,将图片源文件翻转
CGContextScaleCTM(spriteContext, 1.0, -1.0);
CGContextTranslateCTM(spriteContext, 0, -rect.size.height);
使用矩阵实现
顶点着色器
attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;
uniform mat4 rotateMatrix;
void main()
{
vec4 vPos = position;
vPos = vPos * rotateMatrix;
varyTextCoord = textCoordinate;
gl_Position = vPos;
}
实现代码
GLuint rotateMatrix = glGetUniformLocation(self.myPrograme, "rotateMatrix");
//2.获取渲旋转的弧度
float radians = 180 * 3.14159f / 180.0f;
//3.求得弧度对于的sin\cos值
float s = sin(radians);
float c = cos(radians);
//4.因为在3D课程中用的是横向量,在OpenGL ES用的是列向量
/*
参考Z轴旋转矩阵
*/
GLfloat zRotation[16] = {
c,-s,0,0,
s,c,0,0,
0,0,1,0,
0,0,0,1
};
glUniformMatrix4fv(rotateMatrix, 1, GL_FALSE, zRotation);