为什么我的自定义视图不可见?

时间:2017-06-20 12:30:13

标签: ios objective-c opengl-es

我有一个自定义视图,如下所示:

@interface OpenGLCopy () {
    CAEAGLLayer *_eaglLayer;
    EAGLContext *_context;
    GLuint _colorRenderBuffer;
}
@end

@implementation OpenGLCopy

#pragma mark - life cycle
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupLayer];
        [self setupContext];
        [self setupRenderBuffer];
        [self setupFrameBuffer];

        [self render];
    }
    return self;
}


#pragma mark - override
+ (Class)layerClass {
    return [CAEAGLLayer class];
}

#pragma mark - private helper
- (void)setupLayer {
    _eaglLayer = (CAEAGLLayer *)self.layer;
    _eaglLayer.opaque = YES;
}

- (void)setupContext {
    _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    if (!_context) {
        NSLog(@"failed to initialize OpenGLES 2.0 context");
        return ;
    }

    if (![EAGLContext setCurrentContext:_context]) {
        NSLog(@"failed to set current OpenGL context");
        return ;
    }
}


- (void)setupRenderBuffer {
    glGenRenderbuffers(1, &_colorRenderBuffer);
    glBindBuffer(GL_RENDERBUFFER, _colorRenderBuffer);
    [_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
}


- (void)setupFrameBuffer {
    GLuint frameBuffer;
    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _colorRenderBuffer);
}


- (void)render {
    glClearColor(0, 104.0/255.0, 55.0/255.0, 1.0);
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    [_context presentRenderbuffer:GL_RENDERBUFFER];
}

@end

但是当我初始化此视图并将其添加到控制器视图中时,我看不到自定义视图。当我使用视图层次结构进行调试时,自定义视图实际上位于顶部。 谁能告诉我为什么?

1 个答案:

答案 0 :(得分:1)

您应该使用glGetError()检查代码中的错误。这有助于您至少查明问题。

通过这样做,我发现你的错误实际上非常小。绑定渲染缓冲区时调用glBindBuffer。您需要使用glBindRenderbuffer,只需替换

即可
glBindBuffer(GL_RENDERBUFFER, _colorRenderBuffer);

glBindRenderbuffer(GL_RENDERBUFFER, _colorRenderBuffer);