在上一篇中浪册,我們了解了如何給圖形上色崎岂,那么現(xiàn)在我們來做一個(gè)更有趣的事情,給圖形貼上一張圖片(紋理)。
- 加載紋理
- 激活紋理
- 渲染紋理
加載紋理
GLKit給我們提供很方變的方法加載一個(gè)紋理账忘,如果不用系統(tǒng)的方法的,我也可以自己實(shí)現(xiàn)绪穆,大致就是讀取圖片的rgb數(shù)據(jù)纳猫,創(chuàng)建紋理(Texture),將數(shù)據(jù)傳給紋理谈截。
- (void)setupTexture {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"flower" ofType:@"jpg"];
NSError *theError;
_flowerTexture = [GLKTextureLoader textureWithContentsOfFile:filePath options:nil error:&theError];
}
我們還需要一個(gè)紋理的坐標(biāo)來告訴OpenGL怎么去顯示紋理筷屡,紋理的坐標(biāo)左下角是(0,0)右上角是(1簸喂,1)毙死,不過有些系統(tǒng)上的圖片并不是按這樣的坐標(biāo)存儲(chǔ)的,所以當(dāng)顯示的和直接預(yù)覽的圖片效果不一樣時(shí)喻鳄,改一下對(duì)應(yīng)的坐標(biāo)的值就好了扼倘。
- (void)setupVBO {
GLfloat rectangleVertices[] = {
//position texcoord
-0.4, -0.4, 0.0, 0.0, 0.0,
-0.4, -0.8, 0.0, 0.0, 1.0,
0.4, -0.8, 0.0, 1.0, 1.0,
0.4, -0.4, 0.0, 1.0, 0.0,
};
glGenBuffers(1, &_rectangleVBO);
glBindBuffer(GL_ARRAY_BUFFER, _rectangleVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(rectangleVertices), rectangleVertices, GL_STATIC_DRAW);
}
激活紋理
在畫圖形之前,我們激活紋理诽表,并綁定紋理唉锌,片段著色器會(huì)讀取當(dāng)前激活的紋理。
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
GLKView *glView = (GLKView *)self.view;
[EAGLContext setCurrentContext:glView.context];
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
[_rectangleShader prepareToDraw];
glBindBuffer(GL_ARRAY_BUFFER, _rectangleVBO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glActiveTexture(_flowerTexture.target);
glBindTexture(_flowerTexture.target, _flowerTexture.name);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
渲染紋理
接收紋理的坐標(biāo)竿奏,并傳給片段著色器袄简。
attribute vec3 a_Position;
attribute vec2 a_TexCoord;
varying lowp vec2 TexCoord;
void main(void) {
gl_Position = vec4(a_Position, 1.0);
TexCoord = a_TexCoord;
}
片段著色器通過紋理的數(shù)據(jù)和坐標(biāo)計(jì)算出實(shí)際的顏色值。
varying lowp vec2 TexCoord;
uniform sampler2D texture0;
void main(void) {
gl_FragColor = texture2D(texture0, TexCoord);
}
運(yùn)行項(xiàng)目泛啸,可以看到一個(gè)貼上了兩朵花的矩形绿语。
截圖