默認情況下,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>
//三角形頂點數(shù)據(jù)
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環(huán)境
@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. 啟用頂點位置數(shù)組
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模板創(chuàng)建的項目。直接替換GameViewController.m中的內(nèi)容就行。