2010-09-02 137 views

回答

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); 
+0

感谢亲近了!对你非常有帮助。 – SirRatty 2010-09-02 23:44:15

+0

没问题:-)。 – mk12 2010-09-03 00:54:04