OpenGL ES 纹理图片解析第一波 - 无耐地放弃重写这一部分

来源:互联网 发布:网络综艺点击量 编辑:程序博客网 时间:2024/04/29 04:23

可是纹理图片解析这一部分,真的好多东西,之前已有发主要部分,但那个确实经不起推敲,还有好多相关的参数解析,确实搞不太清楚。

所以还是觉得老罗的两个类写的比较内敛:TextureLoader 和 TextureHelper,直接调用一个类方法,传一个图片路径就能得到纹理对象:

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. tempMaterial.textureUnit = [TextureHelper createTexture:textureImagePath isPVR:FALSE];  

细节问题,全部掩藏起来,不失为上等代码与结构。

不过,不要高兴的太早了,如果你的纹理图片不在应用包中,而是在应用沙盒里,那么这样的简单使用,就要出问题了,一看下面代码,就全明白了:

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. @implementation TextureLoader  
  2.   
  3. - (void)loadImage:(NSString *)filepath isPOT:(Boolean)isPOT  
  4. {  
  5.     [self unload];  
  6.   
  7.     NSString* resourcePath = [[NSBundle mainBundle] resourcePath];  
  8.     NSString* fullPath = [resourcePath stringByAppendingPathComponent:filepath];  
  9.   
  10.     UIImage* uiImage = [UIImage imageWithContentsOfFile:fullPath];  

从上面代码中,可以发现,纹理图片都是应用包内的路径,也就是开发应用时直接预置里面的图片资源。

那么我们要想使图片灵活起来,想放哪儿就放哪儿,那就得让其目录可配置,怎么办呢?

有人说,那就把增加个路径属性,或者将 resourcePath 改成类的属性来声明,初始构建时给个默认值是应用包路径,这样如果还是原来的使用方式,默认就是这个路径,保持不变;如果指定了新路径,那么就按新路径来搜索。如下:

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. @interface TextureLoader : NSObject  
  2. @property (nonatomicstrong) NSString* resourcePath;  

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. @implementation TextureLoader  
  2.   
  3. - (id)init {  
  4.       
  5.     self = [super init];  
  6.     if (self) {  
  7.           
  8.         self.resourcePath = [[NSBundle mainBundle] resourcePath];  
  9.     }  
  10.     return self;  
  11. }  
  12.   
  13.   
  14. - (void)loadImage:(NSString *)filepath isPOT:(Boolean)isPOT {  
  15.       
  16.     [self unload];  
  17.       
  18.     NSString* fullPath = [_resourcePath stringByAppendingPathComponent:filepath];  
  19.     UIImage* uiImage = [UIImage imageWithContentsOfFile:fullPath];  
  20.       

经过以上的修修改改,就可以在帮助类中,增加个路径参数了:

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. + (GLuint)createTexture:(NSString *)textureFile isPVR:(Boolean)isPVR {  
  2.   
  3.     return [self createTexture:textureFile textureDir:nil isPVR:isPVR];  
  4. }  
  5.   
  6. + (GLuint)createTexture:(NSString *)textureFile textureDir:(NSString *)textureDir isPVR:(Boolean)isPVR {  
  7.       
  8.     TextureLoader * loader = [[TextureLoader alloc] init];  
  9.     if (nil != textureDir) {  
  10.           
  11.         loader.resourcePath = [NSString stringWithString:textureDir];  
  12.     }  

记得,原来的函数名要保留,如上面的方式,这样原逻辑完全没变,只是多一次调用,对于现在的手机,也是影响不大的。


0 0