iOS OpenGL ES加载纹理(GLKit)
1、准备工作
- 创建UIViewController文件并继承GLKViewController
- 遵守协议GLKViewDelegate
- 实现协议方法**- (void)glkView:(GLKView )view drawInRect:(CGRect)rect*
- 定义属性:*@property (nonatomic,strong) GLKBaseEffect mEffect;
2、初始化上下文对象和被绘制对象参数的设置
- (void)setUpContext{
//初始化上下文对象
EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if(!context){
NSLog(@"fail to create ES context");
}
//被绘制对象参数的设置
GLKView *view = (GLKView *)self.view;
view.context = context;
//颜色格式:RGBA每个颜色通道站8位
view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
//深度格式:24位精度
view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
//设置当前上下文
[EAGLContext setCurrentContext:context];
//开启深度测试
glEnable(GL_DEPTH_TEST);
//清理屏幕(相当于设置屏幕颜色)
glClearColor(1.0, 0.4, 0.3, 1.0);
}
3、设置顶点
- (void)setVertex{
//顶点数据
GLfloat vertexs[] = {
-0.5,0.5,0.0, 0.0,1.0,//左上 + 纹理做点
0.5,0.5,0.0, 1.0,1.0,//右上 + 纹理做点
-0.5,-0.5,0.0,0.0,0.0,//左下 + 纹理做点
0.5,0.5,0.0, 1.0,1.0,//右上 + 纹理做点
0.5,-0.5,0.0, 1.0,0.0,//右下 + 纹理做点
-0.5,-0.5,0.0,0.0,0.0//左下 + 纹理做点
};
//开辟缓冲区
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
//将顶点数据拷贝至缓冲区(相当于将顶点数据从cpu转到gpu)
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexs), vertexs, GL_STATIC_DRAW);
//开启位置属性并赋值至顶点着色器的位置属性(GLKVertexAttribPosition)
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL+0);
//开启纹理坐标属性并赋值至顶点着色器的纹理属性(GLKVertexAttribTexCoord0)
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL+3);
}
4、加载纹理
- (void)loadTexture{
//获取图片路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cTest" ofType:@"jpg"];
//纹理显示属性设置
NSDictionary *option = [NSDictionary dictionaryWithObjectsAndKeys:@(1),GLKTextureLoaderOriginBottomLeft, nil];
//加载纹理信息
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:option error:nil];
GLKBaseEffect *mEffect = [[GLKBaseEffect alloc] init];
mEffect.texture2d0.enabled = GL_TRUE;
mEffect.texture2d0.name = textureInfo.name;
self.mEffect = mEffect;
}
5、遵守协议GLKViewDelegate
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect{
//屏幕显示纹理
glClearColor(0.3, 0.6, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
[self.mEffect prepareToDraw];
glDrawArrays(GL_TRIANGLES, 0, 6);
}
6、效果
- 有空会继续更新使用GLSL方式加载纹理
- 如有错误理解,还请各路大神批评指出
- 转载请标明出处