方法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);
其實兩種方法都一樣。 方法二中圖檔是上下翻轉了, 參考方法一自行修改。