OpenGL ES(embedded system)代表嵌入式系统。
如果我们要画一个图形那么我们就要为这个图形提供数据比如这个图形的像素坐标等。把内存中的数据到展示到显示屏上这个数据移动很耗时,所以我们最好用缓存来存储我们的数据。所以有以下几个函数:
glGenBuffers();step1 生成 为图形处理器控制的缓存生成唯一的标志
glBindBuffer();step2 绑定 告诉openGL ES 接下来的运算要用到一个缓存
glBufferData();step3 缓存数据 为当前绑定的缓存初始化并分配足够的空间
glEnableVertexAttribArray();step4 启用或者禁用 接下来生成的图形到底用不用这个缓存如果是禁用函数为glDisableVertexAttribArray();
glVertexAttribPointer();step5 设置指针 告诉openglES 缓存数据的类型 以及缓存数据的内存偏移
glDrawArrays(GL_TRIANGLES, 0, 3);step6 告诉openGL ES 接下来用绑定并且启用的缓存数据渲染某个场景或者某个场景的一部分
glDeleteBuffers();step7 删除缓存释放相关的资源。
以上的函数是画出一个图到删除这个图形的七大步骤,在走这七大步骤之前我们需要为openGL ES 提供上下文
比如:
GLKView *view=(GLKView *)self.view;
view.context=[[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:view.context];
以下是生成一个简单图形代码的例子:
.h
#import <GLKit/GLKit.h>
@interface FirstViewController : GLKViewController
{
GLuint vertexBufferID;
}
@property(nonatomic, strong)GLKBaseEffect *baseEffect;
@end
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
typedef struct
{
GLKVector3 positionCoords;
}SceneVertex;
static const SceneVertex vertexs[]={
{{-0.5f, -0.5f, 0.0}}, // lower left corner
{{ 0.5f, -0.5f, 0.0}}, // lower right corner
{{-0.5f, 0.5f, 0.0}}
};
- (void)viewDidLoad {
[super viewDidLoad];
GLKView *view=(GLKView *)self.view;
view.context=[[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
[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
// Set the background color stored in the current context
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // background color
// Generate, bind, and initialize contents of a buffer to be
// stored in GPU memory
glGenBuffers(1, // STEP 1
&vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, // STEP 2
vertexBufferID);
glBufferData( // STEP 3
GL_ARRAY_BUFFER, // Initialize buffer contents
sizeof(vertexs), // Number of bytes to copy
vertexs, // Address of bytes to copy
GL_STATIC_DRAW);
}
-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
[self.baseEffect prepareToDraw];
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
GLKView *view=(GLKView *)self.view;
[EAGLContext setCurrentContext:view.context];
if (0!=vertexBufferID) {
glDeleteBuffers(1, &vertexBufferID);
vertexBufferID=0;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end