Search code examples
opengl-esios5glkit

Why is GLKView's DrawableWidth not set in ViewDidLoad?


I'm using GLKit's GLKViewController/GLKView to do some basic OpenGL drawing.

I'd like to setup the ViewPort in the ViewDidLoad method. After reading the GLKView reference, I thought I'd be able to do it like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    if (!self.context) {
        NSLog(@"Failed to create ES context");
    }
    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    glViewport( 0, 0, view.DrawableWidth, view.DrawableHeight );
}

The problem is that both DrawableWidth and DrawableHeight properties are zero. Why is that? When the GLKView calls DrawInRect, they're set and their values are what I would expect.


Solution

  • The GLKView Class Reference says this:

    After this, the view automatically creates or updates the framebuffer object whenever the view must be redrawn.

    The framebuffer hasn't been created by the time you receive viewDidLoad, because the view hasn't needed to be drawn yet. So the dimensions of the framebuffer don't exist either.

    It would be inappropriate for the system to create the framebuffer by this time. The view hasn't been added to the on-screen view hierarchy yet. After it's added to the on-screen view hierarchy, its size might be adjusted, which would require throwing away the old framebuffer and creating a new one.

    The view waits until it is actually asked to draw itself to create the framebuffer so it doesn't waste time creating a framebuffer just to throw away later.