默认情况下,OpenGL ES使用正交的笛卡尔坐标系,其中x轴水平向右,y轴垂直向上,而z轴指向屏幕外面,因此每个点用(x, y, z)三个值表示。这个坐标系的原点默认在屏幕中央,并且屏幕的四个角的坐标从左上角顺时针分别为:(-1.0, 1.0, 0)、(1.0, 1.0, 0.0)、(1.0, -1.0, 0.0)、(-1.0, -1.0, 0.0)。
#import "GameViewController.h"
#import <OpenGLES/ES2/glext.h>
//三角形顶点数据
static const GLKVector3 vertices[] = {
{-0.5f, -0.5f, 0.0f},
{0.5f, -0.5f, 0.0f},
{-0.5f, 0.5f, 0.0f}
};
@interface GameViewController () {
GLuint vertexBufferID;
}
//用于设置通用的OpenGL ES环境
@property (strong, nonatomic) GLKBaseEffect *baseEffect;
//OpenGL ES上下文
@property (strong, nonatomic) EAGLContext *context;
@end
@implementation GameViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//使用支持OpenGL ES2的上下文
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if (!self.context) {
NSLog(@"Failed to create ES context");
}
GLKView *view = (GLKView *)self.view;
view.context = self.context;
view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
[EAGLContext setCurrentContext:self.context];
self.baseEffect = [[GLKBaseEffect alloc] init];
//启用元素的默认颜色
self.baseEffect.useConstantColor = GL_TRUE;
//设置默认颜色
self.baseEffect.constantColor = GLKVector4Make(0.0f, 1.0f, 1.0f, 1.0f);
//设置背景色
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
//1. 生成缓存ID
glGenBuffers(1, &vertexBufferID);
//2. 绑定缓存ID对应的缓存类型
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
//3. 分配缓存空间
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
#pragma mark - GLKView and GLKViewController delegate methods
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
[self.baseEffect prepareToDraw];
//使用背景色清屏
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//4. 启用顶点位置数组
glEnableVertexAttribArray(GLKVertexAttribPosition);
//5. 设置顶点位置指针
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLKVector3), NULL);
//6. 绘制三角形
glDrawArrays(GL_TRIANGLES, 0, 3);
}
- (void)dealloc
{
if ([EAGLContext currentContext] == self.context) {
[EAGLContext setCurrentContext:nil];
}
glDeleteBuffers(1, &vertexBufferID);
vertexBufferID = 0;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if ([self isViewLoaded] && ([[self view] window] == nil)) {
self.view = nil;
if ([EAGLContext currentContext] == self.context) {
[EAGLContext setCurrentContext:nil];
}
self.context = nil;
//释放缓存
glDeleteBuffers(1, &vertexBufferID);
vertexBufferID = 0;
}
}
@end
上面的代码是基于Xcode的iOS应用中OpenGL模板创建的项目。直接替换GameViewController.m
中的内容就行。