iOS OpenGL ES入门-基础渲染1

本文介绍在iOS下通过OpenGL ES简单渲染一个视图出来。

OpenGLView.h
#import 
#import 
#include 
#include 

@interface OpenGLView : UIView {
    
    EAGLContext *context;
    GLuint colorRenderBuffer;
    GLuint framebuffer;
    
}

@end
OpenGLView.m
#import "OpenGLView.h"

@implementation OpenGLView


//设置OpenGLView 的layer层为CAEAGLLayer
+ (Class)layerClass {
    return [CAEAGLLayer class];
}

- (void)setup {
    // 创建一个管理上下文
    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    // 设置其为当前OpenGL 渲染的管理上下文
    [EAGLContext setCurrentContext:context];
    // 创建渲染缓冲区
    glGenRenderbuffers(1, &colorRenderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, colorRenderBuffer);
    // 创建帧缓冲区
    glGenFramebuffers(1, &framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    // 将渲染缓冲区和帧缓冲区关联
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer);
    // 将渲染缓冲区和layer关联在一起(OpenGL ES渲染缓存对象绑定到layer上)
    [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];
    // 检测帧对象是否创建成功
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
    }
    // 清除颜色缓冲区
    glClearColor(1, 1, 0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    // 将渲染缓冲区呈现出来
    [context presentRenderbuffer:GL_RENDERBUFFER];
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];
    [self setup];
}

@end
ViewController.m
#import "ViewController.h"
#import "OpenGLView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    OpenGLView *view = [[OpenGLView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:view];
    
}

@end

你可能感兴趣的:(iOS OpenGL ES入门-基础渲染1)