新建Xcode工程初始化问题:
- (EAGLContext *)glContext
{
if (!_glContext) {
_glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
}
return _glContext;
}
- (void)viewDidLoad {
[super viewDidLoad];
GLKView * viewGl = (GLKView *)self.view;
self.glView = viewGl;
self.glView.context = self.glContext;
viewGl.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888; //颜色缓冲区格式
[EAGLContext setCurrentContext:self.glContext];
}
/**
* 渲染场景代码
*/
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//启动着色器
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
崩溃问题:'-[UIView setContext:]: unrecognized selector sent to instance 0x7fcd35609a10'
解决办法:ViewController 为UIViewController对象,并不是GLKViewController,导致属性context的setter找不到,导致崩溃。将StoryBoard里的ViewController类型改为GLKViewController,此时运行,屏幕为黑色,因为Xib继承的还是GLKViewController,并没有运行在ViewController里面写的初始化代码,因此需要将GLKViewController改成ViewController,再次运行,屏幕会变成紫色。
将ViewController修改成GLKViewController之后,继续崩溃。
崩溃问题:'-[GLKViewController loadView] loaded the "BYZ-38-t0r-view-8bC-Xf-vdC" nib but didn't get a GLKView.'
解决办法:将StoryBoard里ViewController Xib下的View改成GLKView类型
如果Xib用不惯则可以自己创建一个LearnGLViewController会避免以上的问题。
#import <GLKit/GLKit.h>
@interface LearnGLViewController : GLKViewController
@end
#import "LearnGLViewController.h"
@interface LearnGLViewController ()
@property (nonatomic,strong)EAGLContext *glContext;
@property (nonatomic,strong)GLKView *glView;
@end
@implementation LearnGLViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self configContext];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (EAGLContext *)glContext
{
if (!_glContext) {
_glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
}
return _glContext;
}
- (void)configContext
{
GLKView * viewGl = (GLKView *)self.view;
self.glView = viewGl;
self.glView.context = self.glContext;
viewGl.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888; //颜色缓冲区格式
[EAGLContext setCurrentContext:self.glContext];
}
/**
* 渲染场景代码
*/
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//启动着色器
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
@end