我一直在使用这种方法(我想我是从苹果的一个示例代码项目中得到的):
- (void)loadTexture:(NSString *)name intoLocation:(GLuint)location
{
CGImageRef textureImage = [UIImage imageNamed:name].CGImage;
if(textureImage == nil)
{
NSLog(@"Failed to load texture!");
return;
}
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);
//The Fix:
//CGContextClearRect(textureContext, CGRectMake(0.0f, 0.0f, texWidth, texHeight));
CGContextDrawImage(textureContext, CGRectMake(0, 0, (float)texWidth, (float)texHeight), textureImage);
CGContextRelease(textureContext);
glBindTexture(GL_TEXTURE_2D, location);
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);
}
然后我在 initWithCoder
方法中加载纹理:
glGenTextures(NUM_OF_TEXTURES, &textures[0]);
[self loadTexture:@"1.png" intoLocation:textures[0]];
[self loadTexture:@"2.png" intoLocation:textures[1]];
[self loadTexture:@"3.png" intoLocation:textures[2]];
[self loadTexture:@"4.png" intoLocation:textures[3]];
[self loadTexture:@"5.png" intoLocation:textures[4]];
现在这对我来说非常有用,但是当加载的图像包含透明区域时,它们会在其后面显示以前的图像。
例如,如果所有五个图像上都有透明区域:
- 1.png 将按其应有的方式显示。
- 2.png 将与 1.png 一起显示在背景中。
- 3.png 将与 2.png 一起显示,背景为 1.png。
- 等等...
我以为这会出现在我的绘图代码中,但即使我禁用 GL_BLEND,这种情况仍然会发生。我正在使用 GL_TRIANGLE_FAN
使用顶点数组进行绘图。
编辑:进一步说明
这是我在游戏中使用的 3 个纹理:
使用代码加载纹理,在绑定(bind)它们并绘制之后,会发生以下情况:
这当然不是透明度的预期发挥作用。如果有人能提供帮助那就太好了。
谢谢
最佳答案
我也遇到了同样的问题。在将纹理绘制到其中之前,您需要清除 CGContextRef。它只是碰巧保存了最后一个图像,它也可能是未初始化的内存或其他东西。
CGContextClearRect( cgContext, CGRectMake( 0.0f, 0.0f, width, height ) );
在 CGContextDrawImage
之前调用此函数。
关于iPhone OpenGLES 纹理加载透明度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627265/