IOS OpenGLES2.0 入门01 清空屏幕

在IOS中要使用OpenGLES2.0主要有以下几种方法
1.GLKViewController和GLKView
2.CAEAGLLayer+EAGLContext

我们主要介绍第2种办法CAEAGLLayer+EAGLContext

关于OpenGL的 RenderBuffer 和 FrameBuffer
简单的说, RenderBuffer就是我们看到的显示在屏幕上的那些数据
但是这些数据是哪来的呢, RenderBuffer = FrameBuffer + 光照 + …

正常我们一个OpenGL程序需要一个或多个RenderBuffer, 一个或多个FrameBuffer, 在加上其他的数据
这里我们采用一个RenderBuffer和一个FrameBuffer

RenderBuffer的生成使用glGenRenderBuffer, 生成完后要绑定到GL_RENDERBUFFER这个位置上, 使用glBindRenderBuffer
同理FrameBuffer采用 glGenFrameBuffer和glBindFrameBuffer

前面说了RenderBuffer = FrameBuffer + 光照 + …, 我们需要一个函数把它们关联起来,glFramebufferRenderbuffer

关联GL_RENDERBUFFER为GL_COLOR_ATTACHMENT0
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderBuffer);

IOS 使用OpenGL 还需要用到CAEAGLLayer和EAGLContext

+ (Class) layerClass {
   return [CAEAGLLayer class];
}
_eaglLayer = (CAEAGLLayer *) self.layer;
_eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:_eaglContext];

关联EAGLContext与CAEAGLLayer

[_eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];

我们需要EAGLContext来渲染我们的RenderBuffer到_eaglLayer上, 从而显示到我们屏幕上

[self.eaglContext presentRenderbuffer:GL_RENDERBUFFER];

完整代码

- (void) setupOpenGL {
    _eaglLayer = (CAEAGLLayer *) self.layer;
    _eaglLayer.opaque = YES;

    _eaglLayer.drawableProperties = @{kEAGLDrawablePropertyRetainedBacking: @YES,
                                      kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8};

    _eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    [EAGLContext setCurrentContext:_eaglContext];

    glGenRenderbuffers(1, &_renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, _renderBuffer);

    glGenFramebuffers(1, &_frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);

    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderBuffer);
    [_eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];

}

[EAGLContext setCurrentContext:self.eaglContext];

glViewport(0, 0, self.drawableWidth, self.drawableHeight);
glClearColor(0, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);

[self.eaglContext presentRenderbuffer:GL_RENDERBUFFER];

代码在这

你可能感兴趣的:(IOS,opengl,es,ios,framebuffer,opengl)