天天看点

iphone openGL/ES纹理读取

方法1:

GLuint texture[1];

glGenTextures(1, &texture[0]);

//将这个图像用2D方式纹理映射

glBindTexture(GL_TEXTURE_2D, texture[0]);

//设置过滤器

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

//读取一个图像 bg.png

NSString *path = [[NSBundle mainBundle] pathForResource:@"bg" ofType:@"png"];

NSData *texData = [[NSData alloc] initWithContentsOfFile:path];

UIImage *image = [[UIImage alloc] initWithData:texData];

if (image == nil)

NSLog(@"Do real error checking here");

//读取这个图像的长与高

GLuint width = CGImageGetWidth(image.CGImage);

GLuint height = CGImageGetHeight(image.CGImage);

//设置颜色

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

//分配内存用于画这个图像

void *imageData = malloc( height * width * 4 );

//准备一个context用于映射这个图像

CGContextRef contextX = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );

CGColorSpaceRelease( colorSpace );

CGContextClearRect( contextX, CGRectMake( 0, 0, width, height ) );

CGContextTranslateCTM( contextX, 0, height - height );

//将图像画到context上,实际上就是画到imageData里

CGContextDrawImage( contextX, CGRectMake( 0, 0, width, height ), image.CGImage );

//映射,将图像映射成纹理

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

//释放内存

CGContextRelease(contextX);

free(imageData);

[image release];

[texData release];

方法2:

CGImageRef textureImage = [UIImage imageNamed:@"apple128.png"].CGImage;

NSInteger texWidth = CGImageGetWidth(textureImage);

NSInteger texHeight = CGImageGetHeight(textureImage);

GLubyte *textureData = (GLubyte *)malloc(texWidth * texHeight * 4);

CGContextRef textureContext = CGBitmapContextCreate(

textureData,

texWidth,

texHeight,

8, texWidth * 4,

CGImageGetColorSpace(textureImage),

kCGImageAlphaPremultipliedLast);

CGContextDrawImage(textureContext,

CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight),

textureImage);

CGContextRelease(textureContext);

glGenTextures(1, &tex[0]);

glBindTexture(GL_TEXTURE_2D, tex[0]);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);

free(textureData);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

其实两种方法都一样。 方法二中图片是上下翻转了, 参考方法一自行修改。