GLKit框架对OpenGL ES的操作做了很多的封装,开发者用起来比较方便。下面讲一讲如何使用。
首先自定义一个View,继承自GLKView。
#import
#import
NS_ASSUME_NONNULL_BEGIN
@interface MyView : GLKView
@end
NS_ASSUME_NONNULL_END
新建OpenGL上下文,设置颜色格式:
//新建OpenGLES 上下文
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
self.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888; //颜色缓冲区格式
[EAGLContext setCurrentContext:self.context];
准备顶点数据,并绑定顶点缓存:
//顶点数据,前三个是顶点坐标(x、y、z轴),后面两个是纹理坐标(x,y)
GLfloat vertexData[] =
{
0.5, -0.5, 0.0f, 1.0f, 0.0f, //右下
0.5, 0.5, 0.0f, 1.0f, 1.0f, //右上
-0.5, 0.5, 0.0f, 0.0f, 1.0f, //左上
0.5, -0.5, 0.0f, 1.0f, 0.0f, //右下
-0.5, 0.5, 0.0f, 0.0f, 1.0f, //左上
-0.5, -0.5, 0.0f, 0.0f, 0.0f, //左下
};
//顶点数据缓存
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
设置顶点数据指针:
//设置指针
glEnableVertexAttribArray(GLKVertexAttribPosition);//顶点坐标
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (void*)0);
glEnableVertexAttribArray(GLKVertexAttribTexCoord0); //纹理坐标
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (void*)(3 * sizeof(GLfloat)));
加载图片,生成纹理:
//纹理贴图
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"duck" ofType:@"png"];
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:@(1), GLKTextureLoaderOriginBottomLeft, nil];//GLKTextureLoaderOriginBottomLeft 纹理坐标系是相反的
GLKTextureInfo* textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:options error:nil];
创建着色器:
//着色器
self.effect = [[GLKBaseEffect alloc] init];
self.effect.texture2d0.enabled = GL_TRUE;
self.effect.texture2d0.name = textureInfo.name;
在View中重写drawRect方法,并调用渲染代码以进行绘制:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//启动着色器
[self.effect prepareToDraw];
glDrawArrays(GL_TRIANGLES, 0, 6);
}
下载地址:
https://github.com/whoyouare888/Note/tree/master/OpenGL/OpenGL-GLKit-%E7%BA%B9%E7%90%86