我开始研究我的第一个OpenGL iPhone应用程序,但是我已经遇到了一个早期障碍。
我有一个非常简单的小纹理,我想在2D游戏中用作精灵,但它呈现奇怪的“随机”彩色像素。
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);
}
这种混合功能产生了最好的效果。
请让我知道你认为错了。
非常感谢,这个问题让我疯狂。
答案 0 :(得分:19)
我可以从代码中看到的一个问题是,在绘制图像之前,您不会清除上下文。由于您的图像包含透明区域并且在背景上组成,因此您只需看到malloc分配的内存中的内容。尝试在绘制图像之前将Quartz Blend模式设置为复制:
CGContextSetBlendMode(textureContext, kCGBlendModeCopy);
您也可以使用calloc而不是malloc,因为calloc会为您提供归零内存。
您的OpenGL混合是正确的:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
给你Porter-Duff“OVER”,这是你通常想要的。
答案 1 :(得分:1)
首先尝试删除CGContextRef:
CGContextSetRGBFillColor(ctxt, 1, 1, 1, 0);
CGContextFillRect(ctxt, CGRectMake(0, 0, w, h));
答案 2 :(得分:0)
很可能你的图像有一些带有零alpha值的彩色像素,但由于混合功能你正在显示它们。尝试
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);