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);

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值