- (
GLuint
)setupTextTexture:(
NSString
*)text
{
//0
CGPoint position = CGPointMake(0,0);
// Make a UILabel with the string
UIFont *font = [UIFont fontWithName:@"Georgia" size:12];
CGRect screenBounds = [ [ UIScreen mainScreen ] bounds ];
CGSize maximumSize = CGSizeMake(screenBounds.size.width-50, 9999);
CGSize size = [text sizeWithFont:font
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeClip];
// CGSize size = [text sizeWithFont:font forWidth:12 lineBreakMode:UILineBreakModeClip];
CGRect frame;
frame.origin = position;
frame.size = size;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 10.0f, size.width, size.height)];
label.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
label.text = text;
label.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
label.font = font;
// Make a UIImage with the UILabel
UIGraphicsBeginImageContext(label.frame.size);
[[label layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
// NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test111.png"];
// NSData *imageData = UIImagePNGRepresentation(layerImage);
// [imageData writeToFile:pngPath atomically:YES];
UIGraphicsEndImageContext();
// 1
CGImageRef spriteImage = layerImage.CGImage;
if (!spriteImage) {
NSLog(@"Failed to setup text image %@", text);
exit(1);
}
// 2
size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
GLubyte * spriteData = (GLubyte *) calloc(width*height*4, sizeof(GLubyte));
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4,
CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
// 3
CGContextDrawImage(spriteContext, CGRectMake(0, 0, width, height), spriteImage);
CGContextRelease(spriteContext);
// 4
GLuint texName;
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
free(spriteData);
return texName;
}