在GLSL渲染图片的基础上,看一下分屏滤镜图片的实现。废话不多说,直接上代码。
先来看一下,如果不使用分屏效果,怎么利用GLSL实现一个图片的渲染。
1.首先导入头文件,声明属性:
#import <GLKit/GLKit.h>
//在这里声明了一个顶点坐标纹理坐标的数据结构
typedef struct {
GLKVector3 positionCoord; // 用 (X, Y, Z)表示
GLKVector2 textureCoord; //用 (U, V)或者(S, T)表示
} SenceVertex;
//顶点和纹理坐标
@property (nonatomic, assign) SenceVertex *vertices;
//用于渲染上下文
@property (nonatomic, strong) EAGLContext *context;
// 用于刷新屏幕
@property (nonatomic, strong) CADisplayLink *displayLink;
// 开始的时间戳
@property (nonatomic, assign) NSTimeInterval startTimeInterval;
// 着色器程序
@property (nonatomic, assign) GLuint program;
// 顶点缓存
@property (nonatomic, assign) GLuint vertexBuffer;
// 纹理 ID
@property (nonatomic, assign) GLuint textureID;
2. 设置OpenGL相关初始化
- (void)filterInit {
//1. 初始化上下文并设置为当前上下文
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:self.context];
//2.开辟顶点数组内存空间,4个顶点
self.vertices = malloc(sizeof(SenceVertex) * 4);
//3.初始化顶点(0,1,2,3)的顶点坐标以及纹理坐标
self.vertices[0] = (SenceVertex){{-1, 1, 0}, {0, 1}};
self.vertices[1] = (SenceVertex){{-1, -1, 0}, {0, 0}};
self.vertices[2] = (SenceVertex){{1, 1, 0}, {1, 1}};
self.vertices[3] = (SenceVertex){{1, -1, 0}, {1, 0}};
//4.创建图层(CAEAGLLayer)
CAEAGLLayer *layer = [[CAEAGLLayer alloc] init];
//设置图层frame
layer.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width);
//设置图层的scale
layer.contentsScale = [[UIScreen mainScreen] scale];
//给当前控制器的View添加layer
[self.view.layer addSublayer:layer];
//5.绑定渲染缓冲区、帧缓冲区(bindRenderLayer方法会在后面实现)
[self bindRenderLayer:layer];
//6.获取处理的图片路径
NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"7.jpg"];
//读取图片
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
//将JPG图片转换成纹理图片(createTextureWithImage方法在后面实现)
GLuint textureID = [self createTextureWithImage:image];
//设置纹理ID, 将纹理ID保存,方便后面切换滤镜的时候重用
self.textureID = textureID;
//7.设置视口
glViewport(0, 0, self.drawableWidth, self.drawableHeight);
//8.设置顶点缓冲区
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
GLsizeiptr bufferSizeBytes = sizeof(SenceVertex) * 4;
glBufferData(GL_ARRAY_BUFFER, bufferSizeBytes, self.vertices, GL_STATIC_DRAW);
//9.初始化着色器程序(setupNormalShaderProgram方法会在后面实现)
[self setupNormalShaderProgram]; // 一开始选用默认的着色器
//10.将顶点缓冲保存,直到退出时才释放
self.vertexBuffer = vertexBuffer;
}
绑定渲染缓冲区、帧缓冲区
//绑定渲染缓存区和帧缓存区
- (void)bindRenderLayer:(CALayer <EAGLDrawable> *)layer {
//1.渲染缓冲区,帧缓冲区对象ID
GLuint renderBuffer;
GLuint frameBuffer;
//2.获取帧渲染缓冲区名称
glGenRenderbuffers(1, &renderBuffer);
//绑定渲染缓冲区
glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
//将渲染缓冲区与layer建立连接
[self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer];
//3.获取帧缓冲区名称
glGenFramebuffers(1, &frameBuffer);
//绑定帧缓冲区
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
//将渲染缓冲区附着到帧缓冲区上
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER,
renderBuffer);
}
将获取到的图片转换成纹理图片
- (GLuint)createTextureWithImage:(UIImage *)image {
//1、将 UIImage 转换为 CGImageRef
CGImageRef cgImageRef = [image CGImage];
//判断图片是否获取成功
if (!cgImageRef) {
NSLog(@"Failed to load image");
exit(1);
}
//2、读取图片的大小,宽和高
GLuint width = (GLuint)CGImageGetWidth(cgImageRef);
GLuint height = (GLuint)CGImageGetHeight(cgImageRef);
//获取图片的rect
CGRect rect = CGRectMake(0, 0, width, height);
//获取图片的颜色空间
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//3.获取图片字节数 宽*高*4(RGBA)
void *imageData = malloc(width * height * 4);
//4.创建上下文
/*
参数1:data,指向要渲染的绘制图像的内存地址
参数2:width,bitmap的宽度,单位为像素
参数3:height,bitmap的高度,单位为像素
参数4:bitPerComponent,内存中像素的每个组件的位数,比如32位RGBA,就设置为8
参数5:bytesPerRow,bitmap的没一行的内存所占的比特数
参数6:colorSpace,bitmap上使用的颜色空间 kCGImageAlphaPremultipliedLast:RGBA
*/
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);
//设置图片纹理属性
//5. 获取纹理ID
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
//6.载入纹理2D数据
/*
参数1:纹理模式,GL_TEXTURE_1D、GL_TEXTURE_2D、GL_TEXTURE_3D
参数2:加载的层次,一般设置为0
参数3:纹理的颜色值GL_RGBA
参数4:宽
参数5:高
参数6:border,边界宽度
参数7:format
参数8:type
参数9:纹理数据
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
//7.设置纹理属性
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);
//8.绑定纹理
/*
参数1:纹理维度
参数2:纹理ID,因为只有一个纹理,给0就可以了。
*/
glBindTexture(GL_TEXTURE_2D, 0);
//9.释放context,imageData
CGContextRelease(context);
free(imageData);
//10.返回纹理ID
return textureID;
}
初始化着色器程序
- (void)setupShaderProgramWithName:(NSString *)name {
//1. 获取着色器Program
GLuint program = [self programWithShaderName:name];
//2. 使用 Program
glUseProgram(program);
//3. 获取Position,Texture,TextureCoords 的索引位置
GLuint positionSlot = glGetAttribLocation(program, "Position");
GLuint textureSlot = glGetUniformLocation(program, "Texture");
GLuint textureCoordsSlot = glGetAttribLocation(program, "TextureCoords");
//4.激活纹理,绑定纹理ID
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, self.textureID);
//5.纹理sample,获取纹理采样器
glUniform1i(textureSlot, 0);
//6.打开positionSlot 属性通道
glEnableVertexAttribArray(positionSlot);
//传递数据到positionSlot中(顶点坐标)
glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, positionCoord));
//7.打开textureCoordsSlot 属性通道
glEnableVertexAttribArray(textureCoordsSlot);
//传递数据到textureCoordsSlot(纹理坐标)
glVertexAttribPointer(textureCoordsSlot, 2, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, textureCoord));
//8.保存当前program,界面销毁时释放
self.program = program;
}
链接着色器程序
- (GLuint)programWithShaderName:(NSString *)shaderName {
//1. 编译顶点着色器/片元着色器源文件
GLuint vertexShader = [self compileShaderWithName:shaderName type:GL_VERTEX_SHADER];
GLuint fragmentShader = [self compileShaderWithName:shaderName type:GL_FRAGMENT_SHADER];
//2. 将顶点/片元附着到当前program
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
//3.链接Program
glLinkProgram(program);
//4.检查是否链接link成功
GLint linkSuccess;
glGetProgramiv(program, GL_LINK_STATUS, &linkSuccess);
if (linkSuccess == GL_FALSE) {
GLchar messages[256];
glGetProgramInfoLog(program, sizeof(messages), 0, &messages[0]);
NSString *messageString = [NSString stringWithUTF8String:messages];
NSAssert(NO, @"program链接失败:%@", messageString);
return;
}
//5.返回当前program
return program;
}
编译着色器源文件
- (GLuint)compileShaderWithName:(NSString *)name type:(GLenum)shaderType {
//1.获取shader路径
NSString *shaderPath = [[NSBundle mainBundle] pathForResource:name ofType:shaderType == GL_VERTEX_SHADER ? @"vsh" : @"fsh"];
NSError *error;
NSString *shaderString = [NSString stringWithContentsOfFile:shaderPath encoding:NSUTF8StringEncoding error:&error];
if (!shaderString) {
NSAssert(NO, @"读取着色器shader失败");
return;
}
//2. 根据shaderType创建shader
GLuint shader = glCreateShader(shaderType);
//3.获取shader source源文件
const char *shaderStringUTF8 = [shaderString UTF8String];
int shaderStringLength = (int)[shaderString length];
glShaderSource(shader, 1, &shaderStringUTF8, &shaderStringLength);
//4.编译shader
glCompileShader(shader);
//5.查看编译是否成功
GLint compileSuccess;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileSuccess);
if (compileSuccess == GL_FALSE) {
GLchar messages[256];
glGetShaderInfoLog(shader, sizeof(messages), 0, &messages[0]);
NSString *messageString = [NSString stringWithUTF8String:messages];
NSAssert(NO, @"shader编译失败:%@", messageString);
return;
}
//6.返回shader
return shader;
}
2.开始绘制
开始动画绘制
- (void)startFilerAnimation {
//1.判断displayLink 是否为空
//CADisplayLink 定时器
if (self.displayLink) {
[self.displayLink invalidate];
self.displayLink = nil;
}
//2. 设置displayLink 的方法
self.startTimeInterval = 0;
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeAction)];
//3.将displayLink 添加到runloop 运行循环
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop]
forMode:NSRunLoopCommonModes];
}
- (void)timeAction {
//DisplayLink 的当前时间撮
if (self.startTimeInterval == 0) {
self.startTimeInterval = self.displayLink.timestamp;
}
//使用program
glUseProgram(self.program);
//绑定buffer
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer);
// 传入时间
CGFloat currentTime = self.displayLink.timestamp - self.startTimeInterval;
GLuint time = glGetUniformLocation(self.program, "Time");
glUniform1f(time, currentTime);
//设置清屏颜色
glClearColor(1, 1, 1, 1);
// 清除画布
glClear(GL_COLOR_BUFFER_BIT);
// 重绘
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
//从渲染缓冲区渲染到屏幕上
[self.context presentRenderbuffer:GL_RENDERBUFFER];
}
3.着色器文件
顶点着色器文件
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main (void) {
gl_Position = Position;
TextureCoordsVarying = TextureCoords;
}
片元着色器
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main (void) {
vec4 mask = texture2D(Texture, TextureCoordsVarying);
gl_FragColor = vec4(mask.rgb, 1.0);
}
至此,利用GLSL渲染图片的过程就是这样了,先来看一下效果:
正常效果.png
4.左右二分屏
对于一张图片在分屏的时候,我们需要确认的是要保留图片的那一部分,我是这么理解的,就以下图为例:
接下来我们只需要在片元着色器的代码中来更改纹理的取值范围就可以了,从上图中可以看到,取的区域范围在Y轴上是不变的,变得只是X轴上的区域范围。
对于此次渲染图片的过程我们是利用GL_TRIANGLE_STRIP的方式连接四个顶点,其实在分屏的时候,顶点的坐标是不会改变的,改变的只是纹理的坐标,所以在实现分屏效果的时候,是不需要修改顶点着色器代码部分,只要修改片元着色器代码即可。
片元着色器代码:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
//利用一个临时的二维向量,获取到纹理坐标
vec2 uv = TextureCoordsVarying.xy;
float x;
if (uv.x >= 0.0 && uv.x <= 0.5) {
// 将x坐标的值映射为0.35~0.85
x = uv.x + 0.35;
} else {
x = uv.x - 0.15;
}
//获取纹素
gl_FragColor = texture2D(Texture, vec2(x, uv.y));
//由于y的值没有变,不需要再设y的值
}
宗主的二分屏.png注意:在着色器的代码中,最好不要加中文注释,有可能无法编译程序,此处加注释只是为了便于理解
5.上下三分屏
其实分三屏的原理和分二屏的原理基本一致;假设我们取这个图像的最中间部分,就是1/3~2/3之间的部分。(这次要把宗主的眉眼取出来,哈哈)
下面来修改一下片元着色器中的代码部分:
片元着色器代码:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
float y;
if (uv.y >= 0.0 && uv.y < 1.0/3.0) {
y = uv.y + 1.0/3.0;
} else if(uv.y >2.0/3.0){
y = uv.y - 1.0/3.0;
}else{
y = uv.y;
}
gl_FragColor = texture2D(Texture, vec2(uv.x, y));
}
如果在这里不声明临时变量y,代码部分也可以写成:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
if (uv.y >= 0.0 && uv.y < 1.0/3.0) {
uv.y = uv.y + 1.0/3.0;
} else if(uv.y >2.0/3.0){
uv.y = uv.y - 1.0/3.0;
}
gl_FragColor = texture2D(Texture, uv);
}
看一下效果:
宗主的三分屏.png
6.四分屏
如果把屏幕分成4份,如下图所示:
四分屏.png从上图来看,如果对于每一个小的区域,都让它填充整个纹理,而不是截取一部分,就好像是把纹理缩小到四分之一的大小,似乎看起来更好一些,下面来试下:
片元着色器代码:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main(){
vec2 uv = TextureCoordsVarying.xy;
if (uv.x <= 0.5) {
uv.x = uv.x * 2.0;
} else {
uv.x = (uv.x - 0.5) * 2.0;
}
if (uv.y <= 0.5) {
uv.y = uv.y * 2.0;
} else {
uv.y = (uv.y - 0.5) * 2.0;
}
gl_FragColor = texture2D(Texture, uv);
}
效果展示:
宗主的四分屏.png
7.六分屏
下面再来看下六分屏怎么去处理:为了不想再只是截取宗主的部分面容,所以我想用四分屏的方式来填充纹理,
六分屏.png 感觉图片会被压缩一点(因为我用的宗主的这张图片是正方形的)片元着色器代码:
void main(){
vec2 uv = TextureCoordsVarying.xy;
if (uv.x <= 0.5) {
uv.x = uv.x * 2.0;
} else {
uv.x = (uv.x - 0.5) * 2.0;
}![![分屏滤镜渲染图片.png](https://img.haomeiwen.com/i12791315/715c9db50f3ac403.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://img.haomeiwen.com/i12791315/6373f2ef3a8b1678.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
if (uv.y <= 1.0/3.0) {
uv.y = uv.y * 3.0;
} else if(uv.y > 1.0/3.0 && uv.y <= 2.0/3.0) {
uv.y = (uv.y - 1.0/3.0) * 3.0;
}else{
uv.y = (uv.y - 2.0/3.0) * 3.0;
}
gl_FragColor = texture2D(Texture, uv);
}
来看下效果:
宗主的六分屏.png
8.九分屏
写到这里,感觉接下来实现宗主的九分屏很简单了,其实跟四分屏的原理是差不多的
九分屏.png片元着色器代码:
void main(){
vec2 uv = TextureCoordsVarying.xy;
if (uv.x <= 1.0/3.0) {
uv.x = uv.x * 3.0;
} else if(uv.x > 1.0/3.0 && uv.x <= 2.0/3.0) {
uv.x = (uv.x - 1.0/3.0) * 3.0;
}else{
uv.x = (uv.x - 2.0/3.0) * 3.0;
}
if (uv.y <= 1.0/3.0) {
uv.y = uv.y * 3.0;
} else if(uv.y > 1.0/3.0 && uv.y <= 2.0/3.0) {
uv.y = (uv.y - 1.0/3.0) * 3.0;
}else{
uv.y = (uv.y - 2.0/3.0) * 3.0;
}
gl_FragColor = texture2D(Texture, uv);
}
直接来看效果:
宗主的九分屏.png
下面用一份思维导图来总结一下GLSL渲染图片的流程:
分屏滤镜渲染图片.png
好了,至此分屏滤镜到此结束,其实分屏这个效果算不上什么滤镜吧,只能是一种功能效果(个人意见)。如有不完善和错误的地方还请各位指正。demo地址:https://github.com/Henry-Jeannie/Filters
在此,感谢宗主的图片积极配合(滑稽)。遥映人间冰雪样,暗香幽浮曲临江,遍识天下英雄路,俯首江左有梅郎。
网友评论