OpenGLES 实现系统的imageWithContentsOfFile

闲来无事,最近在研究OpenGLES的东西,发现在游戏开发 音视频 直播等都有着广泛的应用 觉得这是一个可以去研究的方向 这只是我的一个想法 有待考证 如果有什么不对的地方 非常大家在评论区 大家一起交流 批评指正我的误解和不对的地方 废话不说 来干货

图片加载有主要是两种方式 一个是imageNamed 一个是imageWithContenFIle 。imageNamed会缓存到系统的cache中 对于 小图不错 但是对于大图 缓存太多就不太容易被释放 imageWithContenFIle 是直接采用的OpengGL 实现降图片已纹理的形式 渲染到View上面去的 主要是通过OpenGL的定点着色器和片段着色器去修改 代码示例如下 了解更多的内容 可以去学习下OpenGL 函数和 矩阵等相关的一些内容 最终的效果图片
https://github.com/evernoteHW/OpenglImageDemo
重写OpenGLView
<pre><code class="objc">
@interface OpenGLView(){
NSMutableArray * _vboArray;
KSMatrix4 _rotationMatrix;
}
@end
@implementation OpenGLView
#pragma mark- Initilize GL
+ (Class)layerClass {
// Support for OpenGL ES
return [CAEAGLLayer class];
}
- (void)setupLayer
{
_eaglLayer = (CAEAGLLayer*) self.layer;
// Make CALayer visibale
_eaglLayer.opaque = YES;
// Set drawable properties
_eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
}

- (void)setupContext
{
// Set OpenGL version, here is OpenGL ES 2.0
EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
_context = [[EAGLContext alloc] initWithAPI:api];
if (!_context) {
NSLog(@" >> Error: Failed to initialize OpenGLES 2.0 context");
exit(1);
}
// Set OpenGL context
if (![EAGLContext setCurrentContext:_context]) {
_context = nil;
NSLog(@" >> Error: Failed to set current OpenGL context");
exit(1);
}
}

- (void)setupBuffers
{
// Setup color render buffer
glGenRenderbuffers(1, &_colorRenderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _colorRenderBuffer);
[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
// Setup depth render buffer
int width, height;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
// Create a depth buffer that has the same size as the color buffer.
glGenRenderbuffers(1, &_depthRenderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
// Setup frame buffer
//
glGenFramebuffers(1, &_frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
// Attach color render buffer and depth render buffer to frameBuffer
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER, _colorRenderBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, _depthRenderBuffer);
// Set color render buffer as current render buffer
glBindRenderbuffer(GL_RENDERBUFFER, _colorRenderBuffer);
}

- (void)destoryBuffer:(GLuint *)buffer
{
if (buffer && *buffer != 0) {
glDeleteRenderbuffers(1, buffer);
*buffer = 0;
}
}

- (void)destoryBuffers
{
[self destoryBuffer: &_depthRenderBuffer];
[self destoryBuffer: &_colorRenderBuffer];
[self destoryBuffer: &_frameBuffer];
}

- (void)cleanup
{
[self destoryBuffers];
if (_programHandle != 0) {
glDeleteProgram(_programHandle);
_programHandle = 0;
}
if (_context && [EAGLContext currentContext] == _context)
[EAGLContext setCurrentContext:nil];
_context = nil;
}
- (void)setupProgram
{
// Load shaders
//
NSString * vertexShaderPath = [[NSBundle mainBundle] pathForResource:@"VertexShader"
ofType:@"glsl"];
NSString * fragmentShaderPath = [[NSBundle mainBundle] pathForResource:@"FragmentShader"ofType:@"glsl"];
_programHandle = [GLESUtils loadProgram:vertexShaderPath
withFragmentShaderFilepath:fragmentShaderPath];
if (_programHandle == 0) {
NSLog(@" >> Error: Failed to setup program.");
return;
}
glUseProgram(_programHandle);
[self getSlotsFromProgram];
}

#pragma mark - Light

- (void)setupLights
{
// Set up some default material parameters.
//
glUniform3f(_ambientSlot, 0.04f, 0.04f, 0.04f);
glUniform3f(_specularSlot, 0.5, 0.5, 0.5);
glUniform1f(_shininessSlot, 50)
// Initialize various state.
//
glEnableVertexAttribArray(_positionSlot);
glEnableVertexAttribArray(_normalSlot);
glUniform3f(_lightPositionSlot, 1.0, 1.0, 5.0);
glVertexAttrib3f(_diffuseSlot, 0.8, 0.8, 0.8);
}

#pragma mark - Texture

- (void)updateTextureParameter
{
// It can be GL_NICEST or GL_FASTEST or GL_DONT_CARE. GL_DONT_CARE by default.
//
glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
//单独为纹理缩放指定不同的过滤算法
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//为纹理坐标系中每条坐标轴设定不同的wrapping模式
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}

- (void)setupTextures
{
glActiveTexture(GL_TEXTURE0);
glEnableVertexAttribArray(_textureCoordSlot);
glUniform1i(_samplerSlot, 0);
}

#pragma mark - Draw object

- (void)getSlotsFromProgram
{
// Get the attribute and uniform slot from program
//
_projectionSlot = glGetUniformLocation(_programHandle, "projection");
_modelViewSlot = glGetUniformLocation(_programHandle, "modelView");
_normalMatrixSlot = glGetUniformLocation(_programHandle, "normalMatrix");
_lightPositionSlot = glGetUniformLocation(_programHandle, "vLightPosition");
_ambientSlot = glGetUniformLocation(_programHandle, "vAmbientMaterial");
_specularSlot = glGetUniformLocation(_programHandle, "vSpecularMaterial");
_shininessSlot = glGetUniformLocation(_programHandle, "shininess");
_positionSlot = glGetAttribLocation(_programHandle, "vPosition");
_normalSlot = glGetAttribLocation(_programHandle, "vNormal");
_diffuseSlot = glGetAttribLocation(_programHandle, "vDiffuseMaterial");
_textureCoordSlot = glGetAttribLocation(_programHandle, "vTextureCoord");
_samplerSlot = glGetUniformLocation(_programHandle, "Sampler");
}

- (void)setupProjection
{
float width = self.frame.size.width;
float height = self.frame.size.height;
// Generate a perspective matrix with a 60 degree FOV
ksMatrixLoadIdentity(&_projectionMatrix);
float aspect = width / height;
ksPerspective(&_projectionMatrix, 60.0, aspect, 4.0f, 12.0f);
// Load projection matrix
glUniformMatrix4fv(_projectionSlot, 1, GL_FALSE, (GLfloat*)&_projectionMatrix.m[0][0]);
//glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
}

- (void)resetRotation
{
ksMatrixLoadIdentity(&_rotationMatrix);
}

- (void)updateSurface
{
ksMatrixLoadIdentity(&_modelViewMatrix);
ksTranslate(&_modelViewMatrix, 0.0, 0.0, -8);
ksMatrixMultiply(&_modelViewMatrix, &_rotationMatrix, &_modelViewMatrix);
// Load the model-view matrix
glUniformMatrix4fv(_modelViewSlot, 1, GL_FALSE, (GLfloat)&_modelViewMatrix.m[0][0]);
// Load the normal matrix.
// It's orthogonal, so its Inverse-Transpose is itself!
//
KSMatrix3 normalMatrix3;
ksMatrix4ToMatrix3(&normalMatrix3, &_modelViewMatrix);
glUniformMatrix3fv(_normalMatrixSlot, 1, GL_FALSE, (GLfloat
)&normalMatrix3.m[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, [self createTexture:@"flower.jpg"]);
[self updateTextureParameter];
}
- (GLuint)createTexture:(NSString )textureFile
{
NSString
resourcePath = [[NSBundle mainBundle] resourcePath];
NSString* fullPath = [resourcePath stringByAppendingPathComponent:textureFile];
UIImage* uiImage = [UIImage imageWithContentsOfFile:fullPath];
CGImageRef cgImage = uiImage.CGImage;
CGSize originalSize = CGSizeZero;
originalSize.width = CGImageGetWidth(cgImage);
originalSize.height = CGImageGetHeight(cgImage);
int byteCount = originalSize.width * originalSize.height * 4;
unsigned char* data = (unsigned char) calloc(byteCount, 1);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
CGContextRef context = CGBitmapContextCreate(data,
originalSize.width,
originalSize.height,
8,
4 * originalSize.width,
colorSpace,
bitmapInfo);
CGColorSpaceRelease(colorSpace);
CGRect rect = CGRectMake(0, 0, originalSize.width, originalSize.height);
CGContextDrawImage(context, rect, uiImage.CGImage);
CGContextRelease(context);
NSData imageData = [NSData dataWithBytesNoCopy:data length:byteCount freeWhenDone:YES];
GLuint textureHandle = 0;
glGenTextures(1, &textureHandle);
glBindTexture(GL_TEXTURE_2D, textureHandle);
void
pixels = (void
) [imageData bytes];
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, originalSize.width, originalSize.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glGenerateMipmap(GL_TEXTURE_2D);
return textureHandle;
}

- (void)drawSurface
{
const GLfloat vertices[] = {
-2.0, -2.0, 2.0, 0, 0, 1, 0, 1,
-2.0, 2.0, 2.0, 0, 0, 1, 0, 0,
2.0, 2.0, 2.0, 0, 0, 1, 1, 0,
2.0, -2.0, 2.0, 0, 0, 1, 1, 1,
};
const GLushort indices[] = {
// Front face
0, 3, 1, 3, 2, 1
};
// Create the VBO for the vertice.
//
int vertexSize = 8;
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Create the VBO for the triangle indice
int triangleIndexCount = sizeof(indices)/sizeof(indices[0]);
GLuint triangleIndexBuffer;
glGenBuffers(1, &triangleIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangleIndexCount * sizeof(GLushort), indices, GL_STATIC_DRAW);
//////////////////////////
int stride = vertexSize * sizeof(GLfloat);
const GLvoid* normalOffset = (const GLvoid)(3 * sizeof(GLfloat));
const GLvoid
texCoordOffset = (const GLvoid*)(6 * sizeof(GLfloat));
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(_positionSlot, 3, GL_FLOAT, GL_FALSE, stride, 0);
glVertexAttribPointer(_normalSlot, 3, GL_FLOAT, GL_FALSE, stride, normalOffset);
glVertexAttribPointer(_textureCoordSlot, 2, GL_FLOAT, GL_FALSE, stride, texCoordOffset);
// Draw the triangles.
//
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleIndexBuffer);
glDrawElements(GL_TRIANGLES, triangleIndexCount, GL_UNSIGNED_SHORT, 0);
}

- (void)render
{
if (_context == nil)
return;
glClearColor(0.0f, 1.0f, 0.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Setup viewport
//
glViewport(0, 0, self.frame.size.width, self.frame.size.height);
[self updateSurface];
[self drawSurface];
[_context presentRenderbuffer:GL_RENDERBUFFER];
}

#pragma mark
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setupLayer];
[self setupContext];
[self setupProgram];
[self setupProjection];
[self setupLights];
[self setupTextures];
[self resetRotation];
[GLESUtils printExtensions];
}
return self;
}

- (void)layoutSubviews
{
[EAGLContext setCurrentContext:_context];
glUseProgram(_programHandle);
[self destoryBuffers];
[self setupBuffers];
[self render];
}
@end</code></pre>


Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容