1、定义传入着色器的顶点数据及索引
//传入结构体
typedef struct {
float Position[];
float TexCoord[];
} Vertex;
//顶点数据
const Vertex Vertices[] = {
{{, -, }, {, }},
{{, , },{, }},
{{-, , }, {, }},
{{-, -, },{, }},
};
//顶点索引
const GLubyte Indices[] = {
, , ,
, ,
};
2、生成图片纹理并获得其索引 方法
+ (GLuint)setupTexture:(UIImage *)pImage { CGImageRef spriteImage = pImage.CGImage;
if (!spriteImage) {
NSLog(@"Failed to load image ");
exit();
} size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage); GLubyte * spriteData = (GLubyte *) calloc(width*height*, sizeof(GLubyte)); CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, , width*,
CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast); CGContextDrawImage(spriteContext, CGRectMake(, , width, height), spriteImage); CGContextRelease(spriteContext); GLuint texName;
//生成纹理数
glGenTextures(, &texName);
glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//生成图片纹理
glTexImage2D(GL_TEXTURE_2D, , GL_RGBA, width, height, , GL_RGBA, GL_UNSIGNED_BYTE, spriteData); free(spriteData);
return texName;
}
3、获取传入GLSL的槽位
//获得图片纹理索引
_imageTexture = [OpenGLHelper setupTexture:pImage];
//获得在GLSL中纹理的索引
_texCoordSlot = glGetAttribLocation(_programHandle, "TexCoordIn");
glEnableVertexAttribArray(_texCoordSlot);
_textureUniform = glGetUniformLocation(_programHandle, "Texture");
//获得GLSL中顶点的索引
_positionSlot = glGetAttribLocation(_programHandle, "vPosition");
4、在render(渲染)方法中加入
//传入顶点着色器的数据
glVertexAttribPointer(_positionSlot, , GL_FLOAT, GL_FALSE,
sizeof(Vertex), );
glVertexAttribPointer(_texCoordSlot, , GL_FLOAT, GL_FALSE,
sizeof(Vertex), (GLvoid*) (sizeof(float) *
)); glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _imageTexture);
glUniform1i(_textureUniform, ); // 设置边缘截取模式 防止图片读取有问题
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glDrawElements(GL_TRIANGLES, sizeof(Indices)/sizeof(Indices[]),
GL_UNSIGNED_BYTE, );