OpenGL ES載入紋理
阿新 • 來源:網路 • 發佈:2021-02-09
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方式載入紋理
- 如有錯誤理解,還請各路大神批評指出
- 轉載請標明出處
