前言
学习OpenGL ES的过程,主要是看 《OpenGL ES应用开发指南 ios卷》这本书,这本书里面对于OpenGL ES在ios上的应用还是介绍的比较全面。目标绘制一个三角形在手机上,这个也是上面书籍的一个demo, 项目地址:这里
使用框架
通过GLKit,该框架是ios自带的能够快速上手使用OpenGL ES 框架,它的好处就是 隐藏了一些与View交互和Shader的一些细节,坏处就是实际应用的灵活性比较差,在实际开发中可能用的比较少,比较适合做为一个入门学习OpengGL ES 的框架
实现代码
1.初始化过程
//由于我们继承了GLKViewController,因此当前View是GLKView,
//使用GLKView的好处是,它为我们封装了Op//engl如何将图像渲染到View上的过程
GLKView *view = (GLKView *)self.view;
// 初始化Context
view.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
// 设置当前的Context
[EAGLContext setCurrentContext:view.context];
// 创建渲染类
self.baseEffect = [[GLKBaseEffect alloc] init];
// 设定渲染类使用的颜色,使用固定颜色
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(
1.0f, // Red
1.0f, // Green
1.0f, // Blue
1.0f);// Alpha
// 设定画布的背景颜色
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Generate, bind, and initialize contents of a buffer to be
// stored in GPU memory
// 执行书上介绍的6步操作,生成,绑定,初始化数据到缓存中,在实际应用中并不一定严格会这样操作,
// 因为对于y音视频来说,我们不需要经常改变顶点坐标和纹理坐标,所有在性能上来说使用缓存的影响有限
glGenBuffers(1, // STEP 1
&vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, // STEP 2
vertexBufferID);
glBufferData( // STEP 3
GL_ARRAY_BUFFER, // Initialize buffer contents
sizeof(vertices), // Number of bytes to copy
vertices, // Address of bytes to copy
GL_STATIC_DRAW); // Hint: cache in GPU memory
2.代理方法中绘制
// GLView的回调方法,这个方法会根据屏幕刷新率来调用,我们需要做的是在这个回调函数里更新我们的界面
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
// 渲染类做一些准备工作
[self.baseEffect prepareToDraw];
// 清掉缓存
glClear(GL_COLOR_BUFFER_BIT);
// Enable use of positions from bound vertex buffer
glEnableVertexAttribArray( // STEP 4
GLKVertexAttribPosition);
// 描叙如何使用缓存数据
glVertexAttribPointer( // STEP 5
GLKVertexAttribPosition,
3, // three components per vertex
GL_FLOAT, // data is floating point
GL_FALSE, // no fixed point scaling
sizeof(SceneVertex), // no gaps in data
NULL); // NULL tells GPU to start at
// beginning of bound buffer
// Draw triangles using the first three vertices in the
// currently bound vertex buffer
glDrawArrays(GL_TRIANGLES, // STEP 6
0, // Start with first vertex in currently bound buffer
3); // Use three vertices from currently bound buffer
}
3.一些销毁工作
// 当界面不可见时时需要销毁缓存
// Make the view's context current
GLKView *view = (GLKView *)self.view;
[EAGLContext setCurrentContext:view.context];
// Delete buffers that aren't needed when view is unloaded
if (0 != vertexBufferID)
{
glDeleteBuffers (1, // STEP 7
&vertexBufferID);
vertexBufferID = 0;
}
// Stop using the context created in -viewDidLoad
((GLKView *)self.view).context = nil;
[EAGLContext setCurrentContext:nil];
总结
在ios13上写这段代码的时候,发现GLKit已经在ios12被苹果废除掉了,现在苹果主推的已经转到自家的Matel上去了 ,但是也没关系,图像开发的这种流程变化也不大,趁着现在还可以用,可以先用来学习一下。