Loading png images...

Discussion in 'iOS Programming' started by Soulstorm, May 23, 2009.

  1. Soulstorm macrumors 68000

    Soulstorm

    Joined:
    Feb 1, 2005
    #1
    I am using the following code to load png textures:

    Code:
    - (void)loadTexture:(NSString *)name intoLocation:(GLuint)location {
    	
    	CGImageRef textureImage = [UIImage imageNamed:name].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);
    	
    	// Rotate the image
    	CGContextTranslateCTM(textureContext, 0, texHeight);
    	CGContextScaleCTM(textureContext, 1.0, -1.0);
    	
    	CGContextDrawImage(textureContext, CGRectMake(0.0, 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);
    }
    The problem is that although the image is loaded correctly in some situations, it does not work on others on PNG images. Sometimes they are displayed as a white area. I am including 2 png images. The first one works, and the second doesn't.

    Any ideas on what may be wrong?
     

    Attached Files:

  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    Does the second one have alpha values? If so you need to setup the blending options in OpenGL. This is something I used in a recent (Mac) project (note: I'm an OpenGL newbie):

    Code:
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    ...
    
    glDisable(GL_BLEND);
     
  3. Soulstorm thread starter macrumors 68000

    Soulstorm

    Joined:
    Feb 1, 2005
    #3
    Actually is was a matter of OpenGL's limitation that commands using textures that have a power of 2.

    But how can I bypass that limitation?
     

Share This Page