iPhone PNG 加载 alpha 伪影

标签 iphone opengl-es uiimage png alpha

我正在加载 PNG 纹理,但在具有大量 Alpha 透明度的图像上出现奇怪的伪影。

这是源png: /image/cqLTt.jpg

这是游戏中白色背景的纹理: /image/mjPE9.jpg

这是我用来加载图像的代码:

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);

从 UIImage 中获取 pImageData 的内存后,它的内存已经困惑了,第一个像素正确地是红色,但下一个像素应该是透明的(如第三个像素)

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

我在build设置中关闭了 png 压缩,但它没有产生任何影响。有人有主意吗? alpha/opengl 设置似乎是正确的,因为将此纹理更改为 TGA 或压缩为 PVRTC 会产生正确的图像。

最佳答案

啊哈,在这里找到了答案: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);

关于iPhone PNG 加载 alpha 伪影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271829/

相关文章:

android - 在 Android 和 iOS 设备上保存纹理的 GPU 内存限制

iphone - 在 iPhone 上渲染为非二次方纹理

ios - 在 RubyMotion 中捕获 UIView

iphone - 消除自定义 UITableViewCell 上不需要的填充

ios - 底部 2 行未在我的 tableview 中注册触摸

ios - 在 ios 的 UIWebview 中调用 javaScript

ios - 拥有@2x 图像 Assets 而没有@1x Assets

iphone - 将数据从一个表插入到另一个表

ios - glReadPixels 只保存 1/4 屏幕大小的快照

swift - Swift 中的 CIDetector 透视和裁剪