【问题标题】:iPhone OpenGLES texture loading issue with transparency具有透明度的 iPhone OpenGLES 纹理加载问题
【发布时间】:2010-09-03 16:32:12
【问题描述】:

我一直在使用这种方法(我想我是从 Apple 的一个示例代码项目中得到的):

- (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 将在背景中显示 2.png,在背景中显示 1.png。
  • 等等……

我以为这会出现在我的绘图代码中,但即使我禁用 GL_BLEND,这仍然会发生。我正在使用GL_TRIANGLE_FAN 使用顶点数组进行绘图。

编辑:进一步解释

这是我在游戏中使用的 3 种纹理:

使用代码加载纹理并绑定它们并绘制后,会发生以下情况:

这肯定不是透明功能的预期。如果有人可以提供帮助,那就太好了。

谢谢

【问题讨论】:

  • 这是按预期发挥作用的透明度 - 让您可以看到下面的图层。我不确定这里的问题是什么。
  • 我已经更新了问题,使其更易于理解。第二张图片是我绑定每个纹理时发生的情况。所以对于“Img 3”,我只会寻找要绘制的红色方块和“Img 2” - 要绘制的绿色方块,等等......

标签: iphone objective-c opengl-es textures transparent


【解决方案1】:

我遇到了同样的问题。在将纹理绘制到其中之前,您需要清除 CGContextRef。它恰好保存了最后一张图像,也可能是未初始化的内存或其他东西。

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

在您的 CGContextDrawImage 之前拨打此电话。

【讨论】:

  • 谢谢!不知道为什么我使用的示例中没有包含它。无论如何解决了我的问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多