-1

I'm trying to load .png file as texture to my cube.

[self loadTexture:&myTexture fromFile:@"my_png.png"];
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE);

This is a function to load it, but unfortunatelly it's not working.

 - (void)loadTexture:(GLuint *)newTextureName fromFile:(NSString *)fileName {
// Load image from file and get reference
UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle]   pathForResource:fileName ofType:nil]];
CGImageRef imageRef = [image CGImage];

if(imageRef) {
    // get width and height
    size_t imageWidth = CGImageGetWidth(imageRef);
    size_t imageHeight = CGImageGetHeight(imageRef);

    GLubyte *imageData = (GLubyte *)malloc(imageWidth * imageHeight * 4);
    memset(imageData, 0, (imageWidth * imageHeight * 4));

    CGContextRef imageContextRef = CGBitmapContextCreate(imageData, imageWidth, imageHeight, 8, imageWidth * 4, CGImageGetColorSpace(imageRef), kCGImageAlphaPremultipliedLast);

    // Make CG system interpret OpenGL style texture coordinates properly by inverting Y axis
    CGContextTranslateCTM(imageContextRef, 0, imageHeight);
    CGContextScaleCTM(imageContextRef, 1.0, -1.0);

    CGContextDrawImage(imageContextRef, CGRectMake(0.0, 0.0, (CGFloat)imageWidth, (CGFloat)imageHeight), imageRef);

    CGContextRelease(imageContextRef);

    glGenTextures(1, newTextureName);

    glBindTexture(GL_TEXTURE_2D, *newTextureName);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

    free(imageData);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  }
}

Have you got any idea to fix this problem?

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • Welcome to Stack Overflow! You'll get more/better answers by describing your problem in more detail. *How* is it not working? In the meantime, you might want to look into the `GLKTextureLoader` class that makes all this easier. – rickster Oct 17 '13 at 23:27

1 Answers1

0
        Class loaderClass = (NSClassFromString(@"GLKTextureLoader"));
        if (loaderClass != nil )
        {
            NSError* error = nil;

            NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
                [NSNumber numberWithBool: mipmap_levels > 0], GLKTextureLoaderGenerateMipmaps,
                [NSNumber numberWithBool:YES], GLKTextureLoaderApplyPremultiplication,
                nil
            ];

            GLKTextureInfo* info = [loaderClass textureWithContentsOfFile: path.NSStringValue() options: options error: &error];
            if (info && !error)
            {}  

If info is not null and no error then info will hold all the information you need.

Emblazed
  • 63
  • 5