在GLSL渲染圖片的基礎上,看一下分屏濾鏡圖片的實現。廢話很少說,直接上代碼。git
先來看一下,若是不使用分屏效果,怎麼利用GLSL實現一個圖片的渲染。github
#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;
複製代碼
- (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 {
//一、將 UIImage 轉換爲 CGImageRef
CGImageRef cgImageRef = [image CGImage];
//判斷圖片是否獲取成功
if (!cgImageRef) {
NSLog(@"Failed to load image");
exit(1);
}
//二、讀取圖片的大小,寬和高
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;
}
複製代碼
初始化着色器程序bash
- (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;
}
複製代碼
編譯着色器源文件oop
- (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;
}
複製代碼
開始動畫繪製動畫
- (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];
}
複製代碼
頂點着色器文件ui
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main (void) {
gl_Position = Position;
TextureCoordsVarying = TextureCoords;
}
複製代碼
片元着色器atom
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渲染圖片的過程就是這樣了,先來看一下效果:
對於一張圖片在分屏的時候,咱們須要確認的是要保留圖片的那一部分,我是這麼理解的,就如下圖爲例:
這張圖片,宗主的臉的位置是稍微偏右的,若是在二分屏的時候,我不想直接取一半,而是把宗主的臉漏出來,那麼接下來我把這張圖片分爲10等份(圖中紅線部分,把宗主的頭像搞這麼花,實在抱歉,胡椒粉勿噴),宗主的臉的位置大概在0.35~0.85之間,(圖中兩條綠色線之間部分)這就是我想要的區域,這也就是咱們在填充紋理的時候,須要填充的區域。 接下來咱們只須要在片元着色器的代碼中來更改紋理的取值範圍就能夠了,從上圖中能夠看到,取的區域範圍在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的值
}
複製代碼
注意:在着色器的代碼中,最好不要加中文註釋,有可能沒法編譯程序,此處加註釋只是爲了便於理解
其實分三屏的原理和分二屏的原理基本一致;假設咱們取這個圖像的最中間部分,就是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);
}
複製代碼
看一下效果:
若是把屏幕分紅4份,以下圖所示:
從上圖來看,若是對於每個小的區域,都讓它填充整個紋理,而不是截取一部分,就好像是把紋理縮小到四分之一的大小,彷佛看起來更好一些,下面來試下:片元着色器代碼:
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);
}
複製代碼
效果展現:
下面再來看下六分屏怎麼去處理:爲了避免想再只是截取宗主的部分面容,因此我想用四分屏的方式來填充紋理,
感受圖片會被壓縮一點(由於我用的宗主的這張圖片是正方形的)片元着色器代碼:
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://upload-images.jianshu.io/upload_images/12791315-715c9db50f3ac403.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://upload-images.jianshu.io/upload_images/12791315-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);
}
複製代碼
來看下效果:
寫到這裏,感受接下來實現宗主的九分屏很簡單了,其實跟四分屏的原理是差很少的
片元着色器代碼:
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);
}
複製代碼
直接來看效果:
下面用一份思惟導圖來總結一下GLSL渲染圖片的流程:
好了,至此分屏濾鏡到此結束,其實分屏這個效果算不上什麼濾鏡吧,只能是一種功能效果(我的意見)。若有不完善和錯誤的地方還請各位指正。 demo地址:github.com/Henry-Jeann…
在此,感謝宗主的圖片積極配合(滑稽)。遙映人間冰雪樣,暗香幽浮曲臨江,遍識天下英雄路,俯首江左有梅郎。