新建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;? //顏色緩沖區(qū)格式
? ? [EAGLContext setCurrentContext:self.glContext];
}
/**
*? 渲染場(chǎng)景代碼
*/
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//啟動(dòng)著色器
? ? ?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對(duì)象,并不是GLKViewController,導(dǎo)致屬性context的setter找不到,導(dǎo)致崩潰。將StoryBoard里的ViewController類型改為GLKViewController,此時(shí)運(yùn)行,屏幕為黑色,因?yàn)閄ib繼承的還是GLKViewController,并沒有運(yùn)行在ViewController里面寫的初始化代碼,因此需要將GLKViewController改成ViewController,再次運(yùn)行,屏幕會(huì)變成紫色。
將ViewController修改成GLKViewController之后,繼續(xù)崩潰。
崩潰問題:'-[GLKViewController loadView] loaded the "BYZ-38-t0r-view-8bC-Xf-vdC" nib but didn't get a GLKView.'
解決辦法:將StoryBoard里ViewController Xib下的View改成GLKView類型
如果Xib用不慣則可以自己創(chuàng)建一個(gè)LearnGLViewController會(huì)避免以上的問題。
#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;? //顏色緩沖區(qū)格式
[EAGLContext setCurrentContext:self.glContext];
}
/**
*? 渲染場(chǎng)景代碼
*/
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//啟動(dòng)著色器
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
@end