Animating text – scrolling text lines

In this recipe we will learn how we can create text scrolling line-by-line.

How to do it…

We will now create an animation with scrolling text. Perform the following steps to do so:

  1. Include the necessary header files.
    #include "cinder/gl/Texture.h"
    #include "cinder/Text.h"
    #include "cinder/Font.h"
    #include "cinder/Utilities.h"
  2. Add the member values.
    vector<gl::Texture> mTextTextures;
    Vec2f   mTextSize;
  3. Inside the setup method we need to generate textures for each line of text.
    setWindowSize(854, 480);
    string font( "Times New Roman" );
    
    mTextSize = Vec2f::zero();
    į
    for(int i = 0; i<5; i++) {
       TextLayout layout;
       layout.clear( ColorA(0.f,0.f,0.f, 0.f) );
       layout.setFont( Font( font, 48 ) );
       layout.setColor( Color( 1, 1, 1 ) );
       layout.addLine( "Animating text " + toString(i) );
       Surface8u rendered = layout.render( true );
       gl::TexturetextTexture = gl::Texture( rendered );
       textTexture.setMagFilter(GL_NICEST);
       textTexture.setMinFilter(GL_NICEST);
       mTextTextures.push_back(textTexture);
       mTextSize.x = math<float>::max(mTextSize.x, 
        textTexture.getWidth());
       mTextSize.y = math<float>::max(mTextSize.y, 
        textTexture.getHeight());
    }
  4. The draw method for this example looks as follows:
    gl::enableAlphaBlending();
    gl::clear( Color::black() );
    gl::setViewport(getWindowBounds());
    gl::setMatricesWindowPersp(getWindowSize());
    
    gl::color(ColorA::white());
    
    float time = getElapsedSeconds()*0.5f;
    float timeFloor = math<float>::floor( time );
    inttexIdx = 1 + ( (int)timeFloor % (mTextTextures.size()-1) );
    float step = time - timeFloor;
    
    gl::pushMatrices();
    gl::translate(getWindowCenter() - mTextSize*0.5f);
    
    float radius = 30.f;
    gl::color(ColorA(1.f,1.f,1.f, 1.f-step));
    gl::pushMatrices();
    gl::rotate( Vec3f(90.f*step,0.f,0.f) );
    gl::translate(0.f,0.f,radius);
    gl::draw(mTextTextures[texIdx-1], Vec2f(0.f, -mTextTextures[texIdx-1].getHeight()*0.5f) );
    gl::popMatrices();
    
    gl::color(ColorA(1.f,1.f,1.f, step));
    gl::pushMatrices();
    gl::rotate( Vec3f(-90.f + 90.f*step,0.f,0.f) );
    gl::translate(0.f,0.f,radius);
    gl::draw(mTextTextures[texIdx], Vec2f(0.f, -mTextTextures[texIdx].getHeight()*0.5f) );
    gl::popMatrices();
    
    gl::popMatrices();

How it works…

What we are doing first inside the setup method in step 3 is generating a texture with rendered text for each line and pushing it to the vector structure mTextTextures.

In step 4 you can find the code for drawing current and previous text to build a continuous looped animation.

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151