每次设备为新的高度和宽度旋转时,您都必须销毁并重建帧缓冲区。使用 layoutsubviews 触发所有这些,当方向改变时调用:
- (void)layoutSubviews {
NSLog(@"layoutSubviews");
[EAGLContext setCurrentContext:_context];
[self destroyFramebuffer];
[self createFramebuffer];
}
- (void)destroyFramebuffer {
NSLog(@"destroy buffer");
glDeleteFramebuffers(1, &viewFramebuffer);
viewFramebuffer = 0;
glDeleteRenderbuffers(1, &viewRenderbuffer);
viewRenderbuffer = 0;
glDeleteRenderbuffers(1, &depthRenderbuffer);
depthRenderbuffer = 0;
}
- (BOOL)createFramebuffer {
NSLog(@"creating buffer");
glGenFramebuffers(1, &viewFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, viewFramebuffer);
glGenRenderbuffers(1, &viewRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
// setup the renderbuffer to the context
[[EAGLContext currentContext] renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRenderbuffer);
// Allocate color buffer backing based on the current layer size (get the current layer size)
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
NSLog(@"backing width: %d height: %d",backingWidth, backingHeight);
// set up the depth buffer
glGenRenderbuffers(1, &depthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, backingWidth, backingHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
[self setupView];
return YES;
}
然后使用 backingWidth 和 backingHeight 重新创建投影矩阵。