将.png文件作为纹理加载到立方体ios

时间:2013-10-17 12:09:34

标签: ios image opengl-es textures cube

我正在尝试将.png文件作为纹理加载到我的多维数据集中。

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

这是一个加载它的功能,但不幸的是它无法正常工作。

 - (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);
  }
}

你有任何想法解决这个问题吗?

1 个答案:

答案 0 :(得分: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)
            {}  

如果info不为null且没有错误,那么info将包含您需要的所有信息。