Click here if you are stuck in someone else's frames.
Drawing Simple Lines

Next, we'll look at how to draw some primitive graphics.  Primitive graphics include lines, circles, and the like.  Once we learn how to draw lines, we can easily use the lines to draw other shapes, such as triangles, boxes, cubes, etc..  Of course, keep in mind that this requires a little bit (well, really quite a bit) of background in mathematics.   To see what I'm talking about, let's look at how math is involved in drawing various lines.

Lines fall into 3 basic categories, if you want to categorize them.  We have horizontal, vertical, and diagonal (angled or sloped) lines.  The horizontal and vertical lines are the easiest to draw because every point in the line either has a common X or a common Y coordinate.


We can write functions that can draw either horizontal or vertical lines very easily since they all have a common X or Y coordinate.  Drawing these lines involve merely setting each pixel along the common X or Y coordinate between the extremes.  The horizontal line between points (1,2) and (10,2), for example, can be drawn by keeping the value for Y constant at 2 and iterating the value for X between 1 through 10.  (Sounds like a good use for the 'for' loop.)  Here are the programs that can draw vertical and horizontal lines:

     /* Draws horizontal lines along the Y axis */

     void DrawHorizLine(int X1, int X2, int Y, unsigned char C)
     {
          int i;                    /* Counts between X1 and X2 */

          if (X2 < X1) {            /* Swap coordinates */
               i  = X1;             /* X1 must be < X2 */
               X1 = X2;
               X2 = i;
          }

          for (i = X1; i <= X2; i++)
               SetPixel(i, Y, C);   /* Set each pixel along the Y axis */
     }


     /* Draws vertical lines along the X axis */

     void DrawVertLine(int X, int Y1, int Y2, unsigned char C)
     {
          int i;                    /* Counts between Y1 and Y2 */

          if (Y2 < Y1) {            /* Swap coordinates */
               i  = Y1;             /* Y1 must be < Y2 */
               Y1 = Y2;
               Y2 = i;
          }

          for (i = Y1; i <= Y2; i++)
               SetPixel(X, i, C);   /* Set each pixel along the X axis */
     }

With these functions, we can draw any horizontal or vertical line, of course these functions do not provide any methods for drawing lines that are sloped or have an angle.  In order to draw these lines and in order to write a single function that can draw all types of lines, horizontal, vertical, and diagonal, we need to use some sort of mathematical method.

Previous Page | Main Page | Next page

Send your questions, comments, or ideas to: garyneal@geocities.com