#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h> @interface OpenGLView : UIView
{
CAEAGLLayer * _eaglLayer;
EAGLContext * _context;
GLuint _colorRenderBuffer;
GLuint _frameBuffer;
} @end
// https://developer.apple.com/library/ios/documentation/OpenGLES/Reference/EAGLContext_ClassRef/index.html
#import "OpenGLView.h" @implementation OpenGLView //!> 1.设置layer class 为 CAEAGLayer
+ (Class)layerClass
{
return [CAEAGLLayer class];
} //!> 2.设置layer为Opaque
- (void)setupLayer
{
_eaglLayer = (CAEAGLLayer *)self.layer;
_eaglLayer.opaque = YES;
} //!> 3.创建OpenGL context
- (void)setupContext
{
//!> 渲染上下文提供的 OpenGL ES 的版本
EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
_context = [[EAGLContext alloc] initWithAPI:api];
if (!_context)
{
NSLog(@"Failed to initialize OpenGLES 2.0 context");
exit();
}
if (![EAGLContext setCurrentContext:_context])
{
NSLog(@"Failed to set current OpenGL context");
exit();
}
} //!> 4.创建render buffer(渲染缓冲区)
- (void)setupRenderBuffer
{
// generate renderbuffer object names
glGenRenderbuffers(, &_colorRenderBuffer);
// bind a renderbuffer to a renderbuffer target
glBindRenderbuffer(GL_RENDERBUFFER, _colorRenderBuffer);
[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
} //!> 5.创建一个frame buffer(帧缓冲区)
- (void)setupFrameBuffer
{
glGenFramebuffers(, &_frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _colorRenderBuffer);
} //!> 6.清理屏幕
- (void)render
{
glClearColor(, 104.0/255.0, 55.0/255.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);//ClearBufferMask
[_context presentRenderbuffer:GL_RENDERBUFFER];
} //!> 实际操作
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self setupLayer];
[self setupContext];
[self setupRenderBuffer];
[self setupFrameBuffer];
[self render];
}
return self;
} - (void)dealloc
{
_context = nil; } @end
05-11 14:58