【发布时间】:2012-02-24 11:10:32
【问题描述】:
我刚刚开始了解 iPhone 上的 OpenGL ES。我试图获得一个非常简单的示例,它设置一个 EAGLContext 和渲染缓冲区,然后简单地使用 glClearColor 来设置屏幕颜色。
我的代码编译并执行,但不幸的是,我看到的不是预期的灰屏,而是带有随机损坏模式的白色图像。我猜我没有正确设置,我希望我的错误对于在这方面有一点经验的人来说是显而易见的。
我的代码是:
AppDelegate.h
#import "GLView.h"
#import <UIKit/UIKit.h>
@interface AppDelegate : NSObject <UIApplicationDelegate> {
@private
UIWindow* m_window;
GLView* m_view;
}
@end
AppDelegate.m
#import "AppDelegate.h"
#import "AppDelegate.h"
#import "GLView.h"
@implementation AppDelegate
- (void) applicationDidFinishLaunching: (UIApplication*) application
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
m_window = [[UIWindow alloc] initWithFrame: screenBounds];
m_view = [[GLView alloc] initWithFrame: screenBounds];
[m_window addSubview: m_view];
[m_window makeKeyAndVisible];
}
- (void) dealloc
{
[m_view release];
[m_window release];
[super dealloc];
}
@end
GLView.h
#import <QuartzCore/QuartzCore.h>
@interface GLView : UIView {
@private
EAGLContext* m_context;
}
- (void) drawView;
@end
GLView.mm
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#import "GLView.h"
@implementation GLView
+ (Class) layerClass
{
return [CAEAGLLayer class];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//Set up the layer and context
CAEAGLLayer* eaglLayer = (CAEAGLLayer*) super.layer;
eaglLayer.opaque = YES;
m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
if (!m_context || ![EAGLContext setCurrentContext:m_context]) {
[self release];
return nil;
}
// Create & bind the color buffer so that the caller can allocate its space.
GLuint renderbuffer;
glGenRenderbuffersOES(1, &renderbuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, renderbuffer);
[m_context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:eaglLayer];
glViewport(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
[self drawView];
}
return self;
}
- (void)drawView
{
glClearColor(0.5f,0.5f,0.5f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
[m_context presentRenderbuffer:GL_RENDERBUFFER_OES];
}
- (void) dealloc
{
if([EAGLContext currentContext] == m_context)
[EAGLContext setCurrentContext:nil];
[m_context release];
[super dealloc];
}
非常感谢您的帮助。
【问题讨论】: