2010-09-02 127 views
2

我一直在使用這種方法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

回答

1

我有這個相同的問題。在將紋理繪製到其中之前,您需要清除CGContextRef。它恰好持有最後一張圖片,它也可能是未初始化的內存或其他東西。

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

在您的CGContextDrawImage之前調用此項權利。

+0

謝謝!不知道爲什麼這不包括在我用過的例子中。無論如何,解決了我的問題:) – 2010-09-03 08:31:12