OpenGL 中任何复杂的图形都是由点,线 和三角形组成的. 那么一个矩形 就需要有两个三角形组成.
纹理, 可以理解为一张图片, 我么可以将整张or部分图片绘制到圆形, 矩形等目标图形中.
下图表示了顶点数据 对应 的纹理中的点.
左侧代表定点数据, 其坐标原点是屏幕中央 ; 右侧图片(纹理), 坐标原点是左下角
GLKBaseEffect让我们避开了写shader Language 着色器语言, 相当于对glsl的封装
typedef struct { GLKVector3 positonCoords;//顶点 GLKVector2 textureCoords;//纹理 }SceneVertex; @interface GLViewController () @property(nonatomic,strong)GLKBaseEffect *baseEffect; @property(nonatomic,assign)GLuint vertexBufferID;//缓存ID属性 @end @implementation GLViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //1.创建OpenGLE ES上下文 GLKView *view = (GLKView *)self.view; view.context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2]; [EAGLContext setCurrentContext:view.context]; //2.GLKBaseEffect属性, 使我们不需要编写shader language(着色器)代码就可以简单完成绘制 self.baseEffect = [[GLKBaseEffect alloc]init]; self.baseEffect.useConstantColor = GL_TRUE;//使用静态颜色绘制 self.baseEffect.constantColor = GLKVector4Make(1.0f, 1.0f, 1.0f, 1.0f);//设置绘制颜色 rgba glClearColor(0.0f, 0.0f, 0.0f, 1.0f);//背景颜色 //3.定点数据 //矩形的六个顶点 static const SceneVertex vertices[] = { {{1, -1, 0.0f,},{1.0f,0.0f}}, //右下 {{1, 1, 0.0f},{1.0f,1.0f}}, //右上 {{-1, 1, 0.0f},{0.0f,1.0f}}, //左上 {{1, -1, 0.0f},{1.0f,0.0f}}, //右下 {{-1, 1, 0.0f},{0.0f,1.0f}}, //左上 {{-1, -1, 0.0f},{0.0f,0.0f}}, //左下 }; //4.生成缓存,并为缓存提供数据 glGenBuffers(1, &_vertexBufferID);//申请一个标识符 glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);//将标识符绑定到GL_ARRAY_BUFFER glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);//复制定点数据从CPU 到 GPU glEnableVertexAttribArray(GLKVertexAttribPosition);//顶点缓存数据 glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL + offsetof(SceneVertex, positonCoords)); glEnableVertexAttribArray(GLKVertexAttribTexCoord0); glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL + offsetof(SceneVertex, textureCoords)); //5.生成纹理 //使用GLkit中的GLKTextureInfo方便的生成图片纹理。 CGImageRef imageRef = [[UIImage imageNamed:@"1.png"]CGImage]; //GLKTextureInfo封装了纹理缓存的信息,包括是否包含MIP贴图 //option 防止图片是倒立了,这个是因为CoreGraphics的坐标系问题 NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:@(1), GLKTextureLoaderOriginBottomLeft, nil]; GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:imageRef options:options error:nil]; self.baseEffect.texture2d0.name = textureInfo.name; self.baseEffect.texture2d0.target = textureInfo.target; //6.代理, 绘制 } //系统给我们回调的绘制消息,该方法会一直被调用,和display方法一致 - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect{ //清除背景色 glClearColor(0.0f,0.0f,0.0f,1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); [self.baseEffect prepareToDraw]; glDrawArrays(GL_TRIANGLES, 0, 6); } - (void)dealloc{ GLKView *view = (GLKView *)self.view; [EAGLContext setCurrentContext:view.context]; if (_vertexBufferID != 0) { glDeleteBuffers(1, &_vertexBufferID); _vertexBufferID = 0; } } @end