通过简单封装理顺了一下思路的简单三角形绘制代码。
#import "ViewController.h"
static const GLKVector3 triangleVertices[3] = {
{0.0f, 0.25f, 0.0f},
{-0.5f, -0.25f, 0.0f},
{0.5f, -0.25f, 0.0f}
};
static const GLKVector4 triangleColors[3] = {
{1.0f, 0.0f, 0.0f, 1.0f},
{0.0f, 1.0f, 0.0f, 1.0f},
{0.0f, 0.0f, 1.0f, 1.0f}
};
@interface ViewController () <GLKViewDelegate>
{
GLuint _triangle;
GLuint _color;
}
@property (strong, nonatomic) GLKBaseEffect *baseEffect;
@end
@implementation ViewController
//创建VBO对象
- (GLuint)createVertexBuffer:(GLsizeiptr)stride //顶点数据大小
numberOfVertices:(GLsizei)count //顶点数
bytes:(const GLvoid *)dataPtr //数组地址
usage:(GLenum)usage { //用途
GLuint name = 0;
glGenBuffers(1, &name);
glBindBuffer(GL_ARRAY_BUFFER, name);
glBufferData(GL_ARRAY_BUFFER, stride * count, dataPtr, usage);
NSAssert(name != 0, @"没有正确产生缓存名称");
return name;
}
//设置绘制对象的属性
- (void)prepareToDrawTarget:(GLuint)name
attrib:(GLuint)index
numberOfCoordinates:(GLint)count
stride:(GLsizei)stride
attribOffset:(GLsizeiptr)offset
enable:(GLboolean)enable {
glBindBuffer(GL_ARRAY_BUFFER, name);
if (enable) {
glEnableVertexAttribArray(index);
}
glVertexAttribPointer(index, //属性类型
count, //顶点数
GL_FLOAT, //数据类型
GL_FALSE, //是否归一化
stride, //顶点数据大小
NULL + offset); //数据偏移量
}
- (void)drawArrayWithMode:(GLenum)mode
startIndex:(GLuint)index
numberOfVertices:(GLsizei)count {
glDrawArrays(mode, index, count);
}
- (void)configOpenGL {
//1. 配置OpenGL上下文
GLKView *glkView = (GLKView *)self.view;
glkView.context = [[EAGLContext alloc] initWithAPI: kEAGLRenderingAPIOpenGLES2];
glkView.drawableDepthFormat = GLKViewDrawableDepthFormat24;
glkView.delegate = self;
[EAGLContext setCurrentContext:glkView.context];
//2. 设置基本的环境参数
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(1.0f, 0.0f, 0.0f, 1.0f);
}
- (void)testBgColor {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}
- (void)viewDidLoad {
[super viewDidLoad];
[self configOpenGL];
[self testBgColor];
//分配缓存区
_triangle = [self createVertexBuffer:sizeof(GLKVector3)
numberOfVertices:3
bytes:triangleVertices
usage:GL_STATIC_DRAW];
_color = [self createVertexBuffer:sizeof(GLKVector4)
numberOfVertices:3
bytes:triangleColors
usage:GL_STATIC_DRAW];
}
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[self.baseEffect prepareToDraw];
//准备顶点数组
[self prepareToDrawTarget:_triangle
attrib:GLKVertexAttribPosition
numberOfCoordinates:3
stride:sizeof(GLKVector3)
attribOffset:0
enable:GL_TRUE];
//准备颜色数组
[self prepareToDrawTarget:_color
attrib:GLKVertexAttribColor
numberOfCoordinates:4
stride:sizeof(GLKVector4)
attribOffset:0
enable:GL_TRUE];
//绘制形状
[self drawArrayWithMode:GL_TRIANGLES
startIndex:0
numberOfVertices:3];
}
@end