简体   繁体   中英

Adding Text to a 2D OpenGL ES 2.0 Object - GLKit - iOS

I have some basic code to draw various polygons (in this case a triangle) :

#import "Triangle.h"

@interface Triangle() {
    GLKBaseEffect * effect;
    NSMutableData *vertexData;

    int numVertices;
}

@property (nonatomic, strong) GLKBaseEffect * effect;
@property (nonatomic, assign) int numVertices;
@property (nonatomic, assign) GLKVector2 *vertices;

@end

@implementation Triangle
@synthesize effect;
@synthesize numVertices;
@synthesize vertices;

- (id)initWithEffect : (GLKBaseEffect *)effectPassed {
    self.effect = effectPassed;
    self.numVertices = 3;

    self.vertices[0] = GLKVector2Make(0,0);
    self.vertices[1] = GLKVector2Make(500, 0);
    self.vertices[2] = GLKVector2Make(500, 500);

    return self;
}

- (GLKVector2 *)vertices {
    if (vertexData == nil)
        vertexData = [NSMutableData dataWithLength:sizeof(GLKVector2)*self.numVertices];
    return [vertexData mutableBytes];
}

-(void)render {

    effect.useConstantColor = YES;
    effect.constantColor = GLKVector4Make(1.0, 0.0, 0.1, 1.0);

    [self.effect prepareToDraw];

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, 0, self.vertices);
    glDrawArrays(GL_TRIANGLE_FAN, 0, self.numVertices);
    glDisableVertexAttribArray(GLKVertexAttribPosition);
}

@end

What I want to do is somehow put some text inside the shape(s). I am thinking along the lines of creating a texture of the same shape (perhaps using Quartz ?) and then using this texture on the shape.

Would anyone be able to advise if this a good way of achieving this, or any other advise ? Is it possible to use Quartz 2D to create an offscreen shape to then save as a UIImage ?

If you want this in a pure OpenGL ES way, you can use freetype library for that purpose. It might be a bit difficult to build and grasp at the beginning. But once you are familiar to it, you can use its pure C API to draw scalable and anti-alised text to OpenGL surface on any device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM