2012-09-04 89 views
2

我加載了PNG紋理,並且在具有大量alpha透明度的圖像上出現奇怪的工件。iPhone PNG加載alpha artifact

這裏是源PNG: http://imgur.com/M8Wj3

這裏是在遊戲中的紋理在白色背景上: http://imgur.com/anliu

下面是我使用加載的圖像的代碼:

NSString* pTextureNameString = [NSString stringWithFormat:@"%s", fileNameWithPath]; 
UIImage* pImage = [UIImage imageNamed:pTextureNameString]; 

GLubyte* pImageData = (GLubyte*)malloc(pImage.size.width * pImage.size.height * 4); 
CGContextRef imageContext = CGBitmapContextCreate(pImageData, pImage.size.width, pImage.size.height, 8, pImage.size.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast); 
CGContextDrawImage(imageContext, CGRectMake(0.0, 0.0, pImage.size.width, pImage.size.height), pImage.CGImage); 
CGContextRelease(imageContext); 

// Build A Texture From The Data 
glGenTextures(1, &m_textureID);         // generate opengl texture id 
glBindTexture(GL_TEXTURE_2D, m_textureID);   // Bind Our Texture 

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering 
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Mipmap Linear Filtering 

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 


glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pImage.size.width, pImage.size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pImageData); 

pImageData的內存在從UIImage中抓取後已經搞亂了,第一個像素是正確的紅色,但下一個像素應該是透明的(像第三個像素)

red ok bad pixel ok  bad pixel etc... 
FF0000FF 05F04713 00000000 70EF7D15 302635B0 02000000 00000000 

我在構建設置中關閉了png壓縮,但它沒有什麼區別。有人有主意嗎? alpha/opengl設置似乎是正確的,因爲將此紋理更改爲TGA或壓縮爲PVRTC會生成正確的圖像。

+0

我道歉,沒想到勾選意味着「接受」。 Stackoverflow應該真的在那裏添加一些文本... –

回答

4

啊哈,在這裏找到了答案:openGL ES textures from PNGs with transparency are being rendered with weird artifacts and driving me nuts!

添加以下行解決了這個問題:

CGContextRef imageContext = CGBitmapContextCreate(pImageData, pImage.size.width, pImage.size.height, 8, pImage.size.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast); 

// Set the correct blending copy mode! 
CGContextSetBlendMode(imageContext, kCGBlendModeCopy); 

CGContextDrawImage(imageContext, CGRectMake(0.0, 0.0, pImage.size.width, pImage.size.height), pImage.CGImage);