Search code examples
opengl-escore-animationcalayertextures

Core Animation / GLES2.0: Getting bitmap from CALayer into GL Texture


I am rewriting in GL some core animation code that wasn't performing fast enough.

on my previous version each button was represented by a CALayer, containing sublayers for the overall shape and the text content.

what I would like to do is set .setRasterize = YES on this layer, force it to render onto its own internal bitmap, then send that over to my GL code, currently:

// Create A 512x512 greyscale texture
{
    // MUST be power of 2 for W & H or FAILS!
    GLuint W = 512, H = 512;

    printf("Generating texture: [%d, %d]\n", W, H);

    // Create a pretty greyscale pixel pattern
    GLubyte *P = calloc( 1, ( W * H * 4 * sizeof( GLubyte ) ) );

    for ( GLuint i = 0; ( i < H ); ++i )
    {
        for ( GLuint j = 0; ( j < W ); ++j )
        {
            P[( ( i * W + j ) * 4  +  0 )] =
            P[( ( i * W + j ) * 4  +  1 )] =
            P[( ( i * W + j ) * 4  +  2 )] =
            P[( ( i * W + j ) * 4  +  3 )] = ( i ^ j );
        }
    }       

    // Ask GL to give us a texture-ID for us to use
    glGenTextures( 1, & greyscaleTexture );

    // make it the ACTIVE texture, ie functions like glTexImage2D will 
    // automatically know to use THIS texture
    glBindTexture( GL_TEXTURE_2D, greyscaleTexture );

    // set some params on the ACTIVE texture
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

    // WRITE/COPY from P into active texture  
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, W, H, 0, GL_RGBA, GL_UNSIGNED_BYTE, P );

    free( P );

    glLogAndFlushErrors();
}

could someone help me patch this together?

EDIT: I actually want to create a black and white mask, so every pixel would either be 0x00 or 0xFF, then I can make a bunch of quads, and for each quad I can set all of its vertices to a particular colour. hence I can easily get different coloured buttons from the same stencil...


Solution

  • http://iphone-3d-programming.labs.oreilly.com/ch05.html#GeneratingTexturesWithQuartz

    GLSprite example here, http://developer.apple.com/library/ios/navigation/#section=Frameworks&topic=OpenGLES