5.OpenGL学习笔记 - 搭建iOS开发环境(不用GLKit框架)

本文不用GLKit框架来搭建OpenGL ES在iOS上的开发环境。

需要在项目中自定义一个UIView的子类,下面所有操作均在这个子类中进行。

导入头文件

#import 

将子类view的layer改变一下:

+ (Class)layerClass{
    return [CAEAGLLayer class];
}

添加一些用到的成员变量:

@implementation EAGLView
{
    EAGLContext *_eaglContext;
    CAEAGLLayer *_eaglLayer;
    GLuint _colorBufferRender;
    GLuint _frameBuffer;

}

设置context,选用版本3的API,context不能跨线程访问:

    //设置context
    _eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
    [EAGLContext setCurrentContext:_eaglContext];

设置layer:

_eaglLayer = (CAEAGLLayer*)self.layer;
_eaglLayer.frame = self.frame;
_eaglLayer.opaque = YES;
_eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithBool:YES],
                                     kEAGLDrawablePropertyRetainedBacking,
                                     kEAGLColorFormatRGBA8,
                                     kEAGLDrawablePropertyColorFormat, nil];

设置renderBuffer和FrameBuffer :

    glGenRenderbuffers(1, &_colorBufferRender);
    glBindRenderbuffer(GL_RENDERBUFFER, _colorBufferRender);
    [_eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];

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

    glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                              GL_COLOR_ATTACHMENT0,
                              GL_RENDERBUFFER,
                              _colorBufferRender);

调用如下代码,将屏幕设置成红色:

    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
    
    glClear(GL_COLOR_BUFFER_BIT);
    
    [_eaglContext presentRenderbuffer:GL_RENDERBUFFER];

经过如上步骤,就设置完了OpenGL在iOS上到环境。

代码地址:

https://github.com/whoyouare888/Note/tree/master/OpenGL/OpenGL%20ES%20%E6%90%AD%E5%BB%BA%E7%8E%AF%E5%A2%83

你可能感兴趣的:(OpenGL)