There are three ways to use OpenGL in iOS, and they all come from the system’s library, GLKit. Let’s take a look at how to use them (we’ll focus on some simple initialization work, step by step).
GLKViewController
Create a controller that inherits from GLKViewController, set an EAGLContext in viewDidLoad, and override the glkView:drawInRect: method to do OpenGL drawing in it.
- (void)viewDidLoad {
[super viewDidLoad];
GLKView *glView = (GLKView *)self.view;
glView.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
}
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
GLKView *glView = (GLKView *)self.view;
[EAGLContext setCurrentContext:glView.context];
glClearColor(1.0.0.1);
glClear(GL_COLOR_BUFFER_BIT);
}
Copy the code
GLKView
Create a view that inherits from GLKView, set an EAGLContext in init, and override drawRect:, and do opengL-related drawing in there as well.
- (instancetype)init
{
self = [super init];
if (self) {[self setupOpenGL];
}
return self;
}
- (void)setupOpenGL {
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
}
- (void)drawRect:(CGRect)rect {
[EAGLContext setCurrentContext:self.context];
glClearColor(0.1.0.1);
glClear(GL_COLOR_BUFFER_BIT);
}
Copy the code
CAEAGLLayer
To initialize OpenGL with CAEAGLLayer, it’s a little bit more complicated, you have to do a couple of things, initialize the Layer, initialize the OpenGL, draw the code.
Initialize the Layer
- (void)setupLayer {
_eaglLayer = (CAEAGLLayer *)self.layer;
}
Copy the code
Initialize OpenGL
Create the context required by OpenGL, create the frame buffer, create the render buffer. The render buffer stores descriptions of colors, depths, templates, etc., and cannot be used directly for rendering. The frame buffer stores pixels that can be displayed directly after processing color, depth, and template description information.
- (void)setupOpenGL {
_glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:_glContext];
glGenFramebuffers(1, &_frameBuffer);
glGenRenderbuffers(1, &_renderBuffer);
}
Copy the code
Draw relevant code
OpenGL is a state machine, which context you set is what context you’re operating on, so we need to make sure we’re operating on the current context.
- (void)drawSome {
[EAGLContext setCurrentContext:_glContext];
glBindRenderbuffer(GL_RENDERBUFFER, _renderBuffer);
// Allocate storage space to the renderBuffer, as iOS requires
BOOL result = [_glContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
if(! result) { printf("failed to renderbufferStorage \n");
}
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderBuffer);
glClearColor(0.0.1.1);
glClear(GL_COLOR_BUFFER_BIT);
[self.glContext presentRenderbuffer:GL_RENDERBUFFER];
}
Copy the code
When you run the project, you’ll see three OpenGL rendered views in red, green and blue. Making the address