简体   繁体   中英

Get empty buffer use glReadPixels with GLKit

In an OpenGL ES app I'm working on, when i use glReadPixels to get pixel but got empty buffer.now i don't know what's wrong in my code。Thanks for any help.

- (void)setTextureImage:(UIImage *)image {
    self.textureID = [self createTextureWithImage:image];

    CAEAGLLayer *layer = [[CAEAGLLayer alloc] init];
    layer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    layer.contentsScale = [[UIScreen mainScreen] scale]; 
    layer.opaque = NO;
    [self.layer addSublayer:layer];
    [self bindRenderLayer:layer];
}

- (void)bindRenderLayer:(CALayer <EAGLDrawable> *)layer {
    
    glGenRenderbuffers(1, &renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
    [self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer];

    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                              GL_COLOR_ATTACHMENT0,
                              GL_RENDERBUFFER,
                              renderBuffer);
}

- (GLint)drawableWidth {
    GLint backingWidth;
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
    return backingWidth;
}

- (GLint)drawableHeight {
    GLint backingHeight;
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
    return backingHeight;
}

above sample code just part of display texture and it's works fine. The renderBuffer and framebuffer is property of my class. sample get pixel code here, buffer is empty after use glReadPixels? Is anything I missed to setup?

    glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
    // I'm try to use one or both of the bind method but not worked
    //glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    NSInteger dataLength = self.drawableWidth * self.drawableHeight * 4;
    GLubyte *buffer = (GLubyte *)malloc(dataLength * sizeof(GLubyte));
    glReadPixels(0,
                 0,
                 self.drawableWidth,
                 self.drawableHeight,
                 GL_RGBA,
                 GL_UNSIGNED_BYTE,
                 buffer);

I found a solution. When you set CAEAGLLayer's drawableProperties like this:

    layer.drawableProperties = @{
        kEAGLDrawablePropertyRetainedBacking: @(YES),
        kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8
    };

kEAGLDrawablePropertyRetainedBacking = YES makes it so you can get the buffer when finshed rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM