OpenGL开发入门

1.OpenGL简介:

       OpenGL ES (OpenGL for Embedded Systems) 是 OpenGL三维图形 API 的子集,针对手机、PDA和游戏主机等嵌入式设备而设计。该API由Khronos集团定义推广,Khronos是一个图形软硬件行业协会,该协会主要关注图形和多媒体方面的开放标准。

         iOS系统默认支持OpenGl ES1.0、ES2.0以及ES3.0 3个版本,三者之间并不是简单的版本升级,设计理念甚至完全不同,在开发OpenGL项目前,需要根据业务需求选择合适的版本。而在iOS上,可以支持opengles3.0的最低环境是iphone5s ios7.0.

初始化EAGLContext时指定ES版本号:

                                                    

EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];

OpenGL坐标系

OpenGL坐标系不同于UIKit坐标系,其实它是这样的:

除了方向,还有一点需要注意,默认情况各个方向坐标值范围为(-1,1),而不是UIKit中的(0,320)。当绘制点(320,0),它并不会出现在屏幕右上角。

2.iOS环境下OpenGL环境搭建:

首先,创建一个single view application工程,然后,引入GlKit和OpenGLES。

紧接着,在ViewController.h文件里引入GLKit/GLKit.h,将ViewController类的父类改成GLKViewController。


#import <UIKit/UIKit.h>

#import <GLKit/GLKit.h>

@interface ViewController : GLKViewController<GLKViewDelegate>

@end

修改viewController中的代码如下:

#import "ViewController.h"
#import <OpenGLES/ES3/gl.h>
#import <OpenGLES/ES3/glext.h>
@interface ViewController ()<GLKViewDelegate>
{
    EAGLContext *context; //EAGLContent是苹果在ios平台下实现的opengles渲染层,用于渲染结果在目标surface上的更新。

}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];//这里用的是opengles3.
    
    if (!context) {
        NSLog(@"Failed to create ES context");
    }
    
    GLKView *view = (GLKView *)self.view;
    view.context = context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
    [EAGLContext setCurrentContext:context];
    glEnable(GL_DEPTH_TEST); //开启深度测试,就是让离你近的物体可以遮挡离你远的物体。
    glClearColor(0.1, 0.2, 0.3, 1); //设置surface的清除颜色,也就是渲染到屏幕上的背景色。
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  //清除surface内容,恢复至初始状态。
}
@end


     再次构建运行,如下图所示:

 参考文献:

               http://www.cocoachina.com/ios/20151123/14116.html

               http://blog.csdn.net/sx1989827/article/details/47304971

原文地址:https://www.cnblogs.com/sunjianfei/p/5655524.html