ebmDevMag.com home
ebm Developer's Magazine
links

developer's mag
main page

article
part 1
part 2
part 3
part 4
part 5
part 6
part 7
part 8
part 9


6 - CWindow Animation

This column's example program is really quite simple - with a combination start and stop button, it simply rotates a line around the center counterclockwise. A scroll bar allows you to control the drawing speed.

Fundamental to the animation is the line drawing:
  void CWindow1::DrawAnimation(int position)
  {
    // our animation - line rotating counter-clockwise
    // draw previous line (if any) in white to erase it
    if (m_prevX1>=0)
      DrawLine( m_prevX1, m_prevY1, m_prevX2, m_prevY2, COLOR_WHITE);
    // make sure 'position' is within array bounds
    position=position%g_maxPosition;
    // get other endpoint by wrapping half way around array
    int pos2=(position+ g_maxPosition /2)%g_maxPosition;
    // save new position to become next call's previous position
    m_prevX1=g_position[position][0];
    m_prevY1=g_position[position][1];
    m_prevX2=g_position[pos2][0];
    m_prevY2=g_position[pos2][1];
    // draw current line
    DrawLine( m_prevX1, m_prevY1, m_prevX2, m_prevY2, COLOR_BLACK);
  }
We have the g_maxPosition array containing 360 x and y screen coordinates, representing points around a circle and spaced one degree apart. The table is an example of speeding up complicated graphics - I calculated the sines and cosines for each point in a spreadsheet, and the pasted the result into the source file. Cosine and sine calculation now becomes a table lookup, speeding up things immensely. The downside is that the table is big and inflexible, but in a production program you could easily generate less data at the cost of more calculations (such as using generic sine and cosine tables, and doing the scaling during the line draw).

Using this table, drawing a line is simple - we select a point, and then another one half way across the array, to create a line that appears to rotate around the center of the display. The only other detail to handle is the previous line drawing. After the first call, each subsequent call needs to erase the previous one - an easy and quick way to do so is to store the previous line's data, and then draw it in the background color (COLOR_WHITE). We then finish off by storing the new values for the next call.

When running the program, you will have trouble spotting the flickering as the one line is erased and the next one is drawn. This is another benefit of using the CWindow routines. Besides the clipping and automatic adjustment for the window frame, it also keeps track of the 'dirty rectangle', and accumulates updates automatically for processing when you exit your MsgHandler(), together improving speed and drawing.

Previous Section
Next Section

Copyright © 2001-2006 ebmDevMag.com - Legal Notice