透明度

问题描述:

我一直在使用这种方法iPhone OpenGLES纹理加载问题(我想我是从苹果的示例代码项目之一):透明度

- (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将在后台以1.png的背景显示2.png。
  • 等...

我想这将是我的绘制代码,但即使我禁用GL_BLEND这仍然发生。我正在使用顶点数组使用GL_TRIANGLE_FAN进行绘制。

编辑:进一步解释

这里有3个纹理我用在我的游戏:

alt text

使用代码加载纹理和结合他们和拉伸之后,这是发生的事情:

alt text

当然这不是透明度充当我ntended。如果任何人都可以提供帮助,那会很棒。

谢谢

+0

这是透明功能的预期 - 让你看透下面的图层。我不确定这里有什么问题。 – 2010-09-02 14:17:06

+0

我已更新问题以便于理解。第二个图像是绑定每个纹理时发生的情况。所以对于'Img 3'我只会寻找红色的方格来画'Img 2' - 绿色的画等等...... – 2010-09-02 14:56:05

我有这个相同的问题。在将纹理绘制到其中之前,您需要清除CGContextRef。它恰好持有最后一张图片,它也可能是未初始化的内存或其他东西。

CGContextClearRect(cgContext, CGRectMake(0.0f, 0.0f, width, height)); 

在您的CGContextDrawImage之前调用此项权利。

+0

谢谢!不知道为什么这不包括在我用过的例子中。无论如何,解决了我的问题:) – 2010-09-03 08:31:12