Mac OS X版本的Texture2D.m,.h可用吗?

时间:2010-09-02 11:36:30

标签: cocoa macos class opengl texture2d

Apple的Texture2D类对于iOS开发人员来说是一个非常有用的工具包。

Q值。是否有可用的Mac OS X版本?

(我用Google搜索但只能通过Cocos2D项目找到iOS实现。)

干杯。

1 个答案:

答案 0 :(得分:4)

你可以为它编写一个方法 - 这就是我使用的方法:

typedef struct {
    void *data;
    GLfloat width;
    GLfloat height;
} TextureData;

+ (TextureData)loadPngTexture:(NSString *)fileName {
    CFURLRef textureURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
              (CFStringRef)fileName,
              CFSTR("png"),
              NULL);
 NSAssert(textureURL, @"Texture name invalid");

 CGImageSourceRef imageSource = CGImageSourceCreateWithURL(textureURL, NULL);
 NSAssert(imageSource, @"Invalid Image Path.");
 NSAssert((CGImageSourceGetCount(imageSource) > 0), @"No Image in Image Source.");
 CFRelease(textureURL);

 CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
 NSAssert(image, @"Image not created.");
 CFRelease(imageSource);

 GLuint width = CGImageGetWidth(image);
 GLuint height = CGImageGetHeight(image);

 void *data = malloc(width * height * 4);

 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
 NSAssert(colorSpace, @"Colorspace not created.");

 CGContextRef context = CGBitmapContextCreate(data,
             width,
             height,
             8,
             width * 4,
             colorSpace,
             kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
 NSAssert(context, @"Context not created.");

 CGColorSpaceRelease(colorSpace);
 // Flip so that it isn't upside-down
 CGContextTranslateCTM(context, 0, height);
 CGContextScaleCTM(context, 1.0f, -1.0f);
 CGContextSetBlendMode(context, kCGBlendModeCopy);
 CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
 CGImageRelease(image);
 CGContextRelease(context);

    return (TextureData){ data, width, height };
}

然后像这样使用它:

TextureData td = [Renderer loadPngTexture:@"atlas"];
// Or use GL_TEXTURE_2D
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, td.width, td.height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, td.data);