iphone - 来自具有透明度的 PNG 的 openGL ES 纹理正在以奇怪的伪影进行渲染,这让我抓狂!

标签 iphone opengl-es quartz-graphics textures

我开始开发我的第一个 OpenGL iPhone 应用程序,但我遇到了早期的障碍。

我有一个非常简单的小纹理,我想在 2D 游戏中将其用作 Sprite ,但它在顶部呈现奇怪的“随机”彩色像素。

http://i40.tinypic.com/2s7c9ro.png <-- 屏幕截图

我感觉这是 Photoshop 的错,所以如果有人对此有任何疑问,请告诉我。

如果它不是 Photoshop 那么它一定是我的代码...所以这是有问题的代码...

- (void)loadTexture {

CGImageRef textureImage = [UIImage imageNamed:@"zombie0.png"].CGImage;

if (textureImage == nil) {
    NSLog(@"Failed to load texture image");
    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);

CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight), textureImage);

CGContextRelease(textureContext);

glGenTextures(1, &textures[0]);

glBindTexture(GL_TEXTURE_2D, textures[0]);

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

glEnable(GL_TEXTURE_2D);

glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

}

此混合函数产生了最佳结果。

请告诉我您认为哪里不对。

非常感谢,这个问题一直让我抓狂。

最佳答案

我从代码中看到的一个问题是,在绘制图像之前没有清除上下文。由于您的图像包含透明区域并且是在背景上合成的,因此您只能看到 malloc 分配的内存中的内容。尝试在绘制图像之前将 Quartz Blend 模式设置为复制:

CGContextSetBlendMode(textureContext, kCGBlendModeCopy);

您还可以使用 calloc 而不是 malloc,因为 calloc 为您提供归零内存。

您的 OpenGL 混合正确:

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

给你波特达夫“OVER”,这是你通常想要的。

关于iphone - 来自具有透明度的 PNG 的 openGL ES 纹理正在以奇怪的伪影进行渲染,这让我抓狂!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1079884/

相关文章:

iphone - 从 XIB 文件过渡到 Storyboard

iphone - 如何在 NSMangedObject 类别中的对多 NSSet 的索引处获取对象

ios - 如何在 mapView ios 上获得我的自定义注释的流畅动画?

ios - 仅当场景数据改变时重绘场景

java - OpenGL ES 渲染循环中的短叠加声音

cocoa - 如何在 Mac OS X 的 Cocoa 上绘制文本内阴影

iphone - UITableViewCell 的宽度

android - 在 OpenGL ES 2.0 着色器中使用纹理作为调色板

iphone - 如何屏蔽 UIImage 以使白色在 iphone 上变得透明?

objective-c - CGEventSetFlags - 发现本地字符串何时需要 shift 修改键