Opengl ES 2.0 - Load PNG with GLKit instead of OpenGL API

804 views Asked by At

I have a piece of code that loads a textures using glTexImage2D like this:

// to test texturing
CGImageRef imageRef = [[UIImage imageNamed:@"Blob.png"] CGImage];
int width = CGImageGetWidth(imageRef);
int height = CGImageGetHeight(imageRef);
GLubyte* textureData = (GLubyte *)malloc(width * height * 4); // if 4 components per pixel (RGBA)

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(textureData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); 
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);

glBindTexture(GL_TEXTURE_2D, 0);

I replaced the code with this, the code doesn throw any error but shows a black image instead.

NSError *error;
GLKTextureInfo *texture = [GLKTextureLoader textureWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Blob.png" ofType:Nil]
                                                               options:Nil
                                                                 error:&error]; assert(!error);

//bind the texture to texture unit 0
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(texture.target, texture.name);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glEnable(texture.target);

glBindTexture(GL_TEXTURE_2D, 0);

What could be the problem?

The project I want to port is at https://github.com/glman74/simpleFBO

2

There are 2 answers

2
uchuugaka On

pathForResource:@"Blob.png" ofType:Nil

Should be pathForResource:@"Blob" ofType:@"png"

And most of the time you should use nil instead if Nil

0
rraallvv On

This is how I've solved it:

This goes in the OpenGL initialisation code

NSError *error;
GLKTextureInfo *texture = [GLKTextureLoader
     textureWithContentsOfFile:
        [[NSBundle mainBundle] pathForResource:@"Blob.png" ofType:Nil]
     options:Nil
     error:&error];

And this goes in the rendering method, in this case glkView:drawInRect:

glBindTexture(GL_TEXTURE_2D, 0);