iOS OpenGL ES3.0入门实践

news/2025/1/22 5:43:50/

一、效果图 

入门实践,做的东西比较简单,效果如下:

二、关于顶点坐标和纹理坐标

绘制图片需要设置顶点坐标和纹理坐标并加载像素数据,之所以要指定两组坐标是因为纹理和顶点使用不同的坐标系,就是告诉OpenGL:把图像的某一区域绘制到屏幕的某一区域,3个点能确定一个三角形区域,我们把一张图分成4个三角形,分别是中心点和每条边点两个顶点组成的三角形,如下图,它图能够帮助你理解后面代码 GLImage.m 中的两组顶点为什么是那样子设置的

三、关于坐标轴方向、投影和坐标映射

具体参考我的另一篇文章Android OpenGL ES 2.0入门实践,主要也是参考的Android官方文档,好在iOS都有对应的函数,就没再仔细看iOS官方文档了。 

四、代码

OpenGL在iOS12 就已经不推荐使用了,官方推荐使用Metal,最近在学习OpenGL ES就在Android和iOS上分别实践了一下,iOS端最简单的方式就是使用GLKit,主要使用GLKViewController这个现成的绘制环境,有了这个环境,就可以直接使用OpenGL的接口进行编码了,平台有更简单易用的 GLKBaseEffect,我没有使用,还是沿用了最基本的流程,使用GL着色器,下面是主要代码:

GlUtil.h

#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLUtil : NSObject+(GLuint)createProgram:(NSString*)vertexShaderCode :(NSString*)fragmentShaderCode;@endNS_ASSUME_NONNULL_END

GLUtil.m

#import "GLUtil.h"@implementation GLUtil+ (NSString *)readShaderSource:(NSString *)bundleFileName {NSString* path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleFileName];NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@", content);return content;
}+ (GLuint)loadShader:(GLenum)type :(const char *)shaderCode {GLuint shader = glCreateShader(type);glShaderSource(shader, 1, &shaderCode, NULL);glCompileShader(shader);GLint commpiled;glGetShaderiv(shader, GL_COMPILE_STATUS, &commpiled);if(!commpiled) {GLint infoLen = 0;glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);if(infoLen > 0) {char* infoLog = malloc(infoLen);glGetShaderInfoLog(shader, infoLen, NULL, infoLog);NSLog(@"%s", infoLog);free(infoLog);glDeleteShader(shader);return 0;}}return shader;
}+ (GLuint)createProgram:(NSString *)vertexShaderFileName :(NSString *)fragmentShaderFileName {GLuint program = glCreateProgram();const char* vertexShaderCode = [[GLUtil readShaderSource:vertexShaderFileName] UTF8String];const char* fragmentShaderCode = [[GLUtil readShaderSource:fragmentShaderFileName] UTF8String];GLuint vertexShader = [self loadShader:GL_VERTEX_SHADER:vertexShaderCode];GLuint fragmentShader = [self loadShader:GL_FRAGMENT_SHADER:fragmentShaderCode];if (vertexShader == 0 || fragmentShader == 0) {return 0;}glAttachShader(program, vertexShader);glAttachShader(program, fragmentShader);glLinkProgram(program);GLint linked;glGetProgramiv(program, GL_LINK_STATUS, &linked);if(!linked) {GLint infoLen = 0;glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);if(infoLen > 0) {char* infoLog = malloc(infoLen);glGetProgramInfoLog(program, infoLen, NULL, infoLog);NSLog(@"%s", infoLog);free(infoLog);glDeleteProgram(program);return 0;}}glDeleteShader(vertexShader);glDeleteShader(fragmentShader);return program;
}@end

vertexShader.glsl

顶点着色器代码 vertexShader.glsl

#version 300 es
uniform mat4 uMVPMatrix;
uniform mat4 translateMatrix;
uniform bool isTranslate;
layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec2 aTextureCoord;
out vec2 vTexCoord;
void main() {if (isTranslate) {gl_Position = uMVPMatrix * translateMatrix * vPosition;} else {gl_Position = uMVPMatrix * vPosition;}vTexCoord = aTextureCoord;
}

fragmentShader.glsl

片段着色器代码 fragmentShader.glsl

#version 300 es
precision mediump float;
uniform bool isTexture;
uniform vec4 vColor;
uniform sampler2D uTextureUnit;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {if(isTexture) {fragColor = texture(uTextureUnit,vTexCoord);} else {fragColor = vColor;}
}

绘制2D纹理的类 GLImage

GLImage.h

#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLImage : NSObject-(void)loadTexture:(NSString*)imageName;-(void)draw:(int)positionHandle :(int)textureHandle :(GLuint*)vbo;@endNS_ASSUME_NONNULL_END

GLImage.m

#import "GLImage.h"
#import <UIKit/UIKit.h>//原文链接:https://blog.csdn.net/gongxiaoou/article/details/89344561//图片尺寸:2385 × 3623
static const float POSITION_VERTEX[]  = {0.0f, 0.0f,     //顶点坐标V01.0f, 1.52f,   //顶点坐标V1-1.0f, 1.52f,   //顶点坐标V2-1.0f, -1.52f,  //顶点坐标V31.0f, -1.52f     //顶点坐标V4
};static const float TEX_VERTEX[]  = {0.5f, 0.5f, //纹理坐标V01.0f, 1.0f,     //纹理坐标V10.0f, 1.0f,     //纹理坐标V20.0f, 0.0f,   //纹理坐标V31.0f, 0.0f    //纹理坐标V4
};static const short VERTEX_INDEX[]  = {0, 1, 2,  //V0,V1,V2 三个顶点组成一个三角形0, 2, 3,  //V0,V2,V3 三个顶点组成一个三角形0, 3, 4,  //V0,V3,V4 三个顶点组成一个三角形0, 4, 1   //V0,V4,V1 三个顶点组成一个三角形
};@interface GLImage()
{GLuint textureID;
}@end@implementation GLImage//原文链接:https://blog.csdn.net/qq_30513483/article/details/101538967
- (void)loadTexture:(NSString *)imageName {UIImage *image = [UIImage imageNamed:imageName];// 将 UIImage 转换为 CGImageRefCGImageRef cgImageRef = [image CGImage];GLuint width = (GLuint)CGImageGetWidth(cgImageRef);GLuint height = (GLuint)CGImageGetHeight(cgImageRef);CGRect rect = CGRectMake(0, 0, width, height);// 绘制图片CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();void *imageData = malloc(width * height * 4);CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8, width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);CGContextTranslateCTM(context, 0, height);CGContextScaleCTM(context, 1.0f, -1.0f);CGColorSpaceRelease(colorSpace);CGContextClearRect(context, rect);CGContextDrawImage(context, rect, cgImageRef);// 生成纹理glGenTextures(1, &textureID);glBindTexture(GL_TEXTURE_2D, textureID);// 将图片数据写入纹理缓存glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);// 设置如何把纹素映射成像素glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);// 解绑glBindTexture(GL_TEXTURE_2D, 0);// 释放内存CGContextRelease(context);free(imageData);
}- (void)draw:(int)positionHandle :(int)textureHandle :(GLuint*)vbo {//顶点坐标glEnableVertexAttribArray(positionHandle);glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);glBufferData(GL_ARRAY_BUFFER, sizeof(POSITION_VERTEX), POSITION_VERTEX, GL_STATIC_DRAW);glVertexAttribPointer(positionHandle, 2, GL_FLOAT, GL_FALSE, 0, 0);//纹理坐标glEnableVertexAttribArray(textureHandle);glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);glBufferData(GL_ARRAY_BUFFER, sizeof(TEX_VERTEX), TEX_VERTEX, GL_STATIC_DRAW);glVertexAttribPointer(textureHandle, 2, GL_FLOAT, GL_FALSE, 0, 0);//激活纹理glActiveTexture(GL_TEXTURE0);//绑定纹理glBindTexture(GL_TEXTURE_2D, textureID);//绘制glDrawElements(GL_TRIANGLES, sizeof(VERTEX_INDEX)/sizeof(short), GL_UNSIGNED_SHORT, VERTEX_INDEX);
}@end

GLViewController.h

#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLViewController : GLKViewController {
}@endNS_ASSUME_NONNULL_END

GLViewController.m

#import "GLViewController.h"
#import "GLUtil.h"
#import "GLImage.h"const int VBO_NUM = 2;static const GLfloat vertices[] = {0.0f,  0.5f, 0.0f,-0.5f, -0.5f, 0.0f,0.5f, -0.5f, 0.0f};@interface GLViewController ()
{GLuint program;int muMVPMatrixHandle;int translateMatrixHandle;int isTranslateHandle;int isTextureHandle;int colorHandle;GLKMatrix4 vMatrix;GLKMatrix4 projMatrix;GLKMatrix4 vPMatrix;GLKMatrix4 translateMatrix;GLuint vbo[VBO_NUM];GLImage* glImage;
}@end@implementation GLViewController- (void)initGL{program = [GLUtil createProgram:@"vertexShader.glsl" :@"fragmentShader.glsl"];glUseProgram(program);muMVPMatrixHandle = glGetUniformLocation(program, "uMVPMatrix");translateMatrixHandle = glGetUniformLocation(program, "translateMatrix");isTranslateHandle = glGetUniformLocation(program, "isTranslate");isTextureHandle = glGetUniformLocation(program, "isTexture");colorHandle = glGetUniformLocation(program, "vColor");glGenBuffers(VBO_NUM, vbo);NSLog(@"%s", __func__);
}- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.GLKView* glView = (GLKView*)self.view;glView.context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES3];[EAGLContext setCurrentContext:glView.context];//这句必须得有,不然画不出来图形[self initGL];glImage = [GLImage new];[glImage loadTexture:@"dog.jpg"];//vMatrix = GLKMatrix4MakeLookAt(0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}- (void) onSurfaceChange:(float)width :(float)height {NSLog(@"%fx%f", width, height);glViewport(0, 0, width, height);//投影矩阵if (width > height) {float ratio = width / height;projMatrix = GLKMatrix4MakeFrustum(-ratio, ratio, -1.0f, 1.0f, 3.0f, 7.0f);} else {float ratio = height / width;projMatrix = GLKMatrix4MakeFrustum(-1.0f, 1.0f, -ratio, ratio, 3.0f, 7.0f);}// Combine the projection and camera view matricesvPMatrix = GLKMatrix4Multiply(projMatrix, vMatrix);
}- (void)viewWillLayoutSubviews {[super viewWillLayoutSubviews];float width = self.view.frame.size.width;float height = self.view.frame.size.height;NSLog(@"%s %fx%f", __func__, width, height);[self onSurfaceChange:width :height];
}- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//    NSLog(@"%s %f", __func__, [[NSDate new] timeIntervalSince1970]);// Apply the combined projection and camera view transformationsglUniformMatrix4fv(muMVPMatrixHandle, 1, false, (float*)&vPMatrix);glClearColor(0.9f, 0.9f, 0.9f, 1.0f);//背景色glClear(GL_COLOR_BUFFER_BIT);//画图片glUniform1i(isTranslateHandle, 0);//禁用矩阵偏移glUniform1i(isTextureHandle, 1);//启用纹理[glImage draw:0 :1 :vbo];double degrees = (long)([[NSDate new] timeIntervalSince1970] * 50) % 360;double radians = degrees * M_PI / 180.0;
//    NSLog(@"degrees=%f", degrees);translateMatrix = GLKMatrix4Translate(GLKMatrix4Identity, cos(radians), sin(radians), 0.0f);glUniformMatrix4fv(translateMatrixHandle, 1, GL_FALSE, (float*)&translateMatrix);glUniform1i(isTranslateHandle, 1);//启用矩阵偏移glUniform1i(isTextureHandle, 0);//禁用纹理glUniform4f(colorHandle, 0.0f, 0.5f, 1.0f, 1.0f);glEnableVertexAttribArray(0);glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);glDrawArrays(GL_TRIANGLES, 0, 3);
}@end

文章来源:https://blog.csdn.net/jjf19891208/article/details/134362510
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1212654.html

相关文章

Android各类View触摸监听器失效

在XML布局中出现重叠的View&#xff0c;位置靠后定义的View会覆盖住位置靠前的View&#xff1b;即靠后的View会拦截触碰事件导致靠前的View无法收到触碰事件&#xff0c;无法触发监听器。 //例.<?xml version"1.0" encoding"utf-8"?> <android…

Module build failed (from ./node_modules/postcss-loader/src/index.js):

出现该错误是你可能没认真看官网的安装配置&#xff0c;可直接看该目录3&#xff0c;一个字一个字看 先安装uview 如果选择v1版本&#xff0c;建议使用npm下载&#xff0c;下面以v1版本为例&#xff0c;使用的是npm下载&#xff0c;导入uview时该文件也在node_modules文件夹里…

mysql 讲解(1)

文章目录 前言一、基本的命令行操作二、操作数据库语句2.1、创建数据库2.2、删除数据库2.3、使用数据库2.4 查看所有数据库 三、列的数据类型3.1 字符串3.2 数值3.3 时间日期3.4 空3.5 int 和 varchar问题总结&#xff1a; 四、字段属性4.1 UnSigned4.2 ZEROFILL4.3 Auto_InCre…

No181.精选前端面试题,享受每天的挑战和学习

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云课上架的前后端实战课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入…

LeetCode257. Binary Tree Paths

文章目录 一、题目二、题解 一、题目 Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: Input: root [1,2,3,null,5] Output: [“1->2->5”,“1->3”] Example 2: Input: root […

【Springboot】基于注解式开发Springboot-Vue3整合Mybatis-plus实现分页查询(二)——前端el-pagination实现

系列文章 【Springboot】基于注解式开发Springboot-Vue3整合Mybatis-plus实现分页查询—后端实现 文章目录 系列文章系统版本实现功能实现思路后端传入的数据格式前端el-table封装axois接口引入Element-plus的el-pagination分页组件Axois 获取后台数据 系统版本 后端&#xf…

高二英语上

unit 1 1.yarn三种意思 1.码&#xff1b; 2.庭院&#xff0c;天井&#xff1b; 3.花园&#xff1b;down**down 在这里是介词,也可以作副词&#xff0c;与 down 相对的是 up。请比较下列两句: 1.Look! Hes driving down the street . 2.Look! Hes driving up the street .这两例…

冯·诺依曼结构

一、约翰冯诺依曼---计算机之父 约翰冯诺依曼&#xff08;John von Neumann&#xff0c;1903年12月28日—1957年2月8日&#xff09;&#xff0c;出生于匈牙利布达佩斯&#xff0c;匈牙利裔美籍数学家、计算机科学家、物理学家和化学家&#xff0c;美国国家科学院院士&#xff…