ylliX - Online Advertising Network

How to display text as texture using GLKit with OpenGL 2.0 in iPhone iOS?

It’s quite easy if you know where to start. There are two ways, you can use UILabel or NSString. With UILabel you can control width and height of rendered texture, also you have words wrap and text aligning.

[cpp]NSError *error;

    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    myLabel.text = @"Hello world!";
    myLabel.font = [UIFont fontWithName:@"Helvetica" size:18];
    myLabel.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];   
    myLabel.backgroundColor = [UIColor clearColor];

    UIGraphicsBeginImageContext(myLabel.bounds.size);

    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 30);

    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);

    [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if (error) {
        NSLog(@"Label::initWithText – Error loading texture from image: %@",error);
    }[/cpp]

So step by step:
1. first we need our UILabel, in CGRectMake we are setting our text size (rectangle)
2. then we need our text to display, also font using UIFont class
3. setting text color is also easy, but then comes little trick – you can use “clearColor” with background to make it transparent
4. next thing is to start new image context with UIGraphicsBeginImageContext
5. next 2 line are important if you don’t want your text to be vertically flipped (third parameter in CGContextTranslateCTM is our UILabel height)
6. then we need to render our label using renderInContext
7. and finally we have ready to use texture using UIImage

One thought on “How to display text as texture using GLKit with OpenGL 2.0 in iPhone iOS?

Leave a Reply