Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Vector Graphics

The available vector drawing methods in the .NET Compact Framework are summarized in Table 15.12 (which appeared earlier in this chapter as Table 15.4 and is repeated here for convenience). As indicated in the table, some shapes are drawn with a pen, a drawing object used for lines. The .NET Compact Framework supports only pens that are 1 pixel wide (unless a programmer drills through to the native GDI drawing support). Other shapes in the table are drawn with a brush. We discussed the three methods for creating brushes earlier in this chapter. We cover the creation of pens in this discussion of vector graphics.

Table 15.12. System.Drawing.Graphics Methods for Vector Drawing

Method

Comment

DrawEllipse

Draws the outline of an ellipse using a pen.

DrawLine

Draws a straight line using a pen.

DrawPolygon

Draws the outline of a polygon using a pen.

DrawRectangle

Draws the outline of a rectangle using a pen.

FillEllipse

Fills the interior of an ellipse using a brush.

FillPolygon

Fills the interior of a polygon using a brush.

FillRectangle

Fills the interior of a rectangle using a brush.

The vector methods with names that start with Draw are those that use a pen to draw a line or a set of connected lines. The call to the DrawRectangle method, for example, draws the outline of a rectangle without touching the area inside the line. If you pass a blue pen to the DrawRectangle method, the result is the outline of a rectangle drawn with a blue line. The .NET Compact Framework supports four line-drawing methods.

Vector methods whose names start with Fill, on the other hand, use a brush to fill in the area bounded by the lines. For example, if you pass a red brush to the FillRectangle method, the result is a solid red rectangle. There are three such methods in the .NET Compact Framework for drawing ellipses, polygons, and rectangles.

The Draw and Fill methods complement each other. You could, for example, pass a red brush to the FillRectangle method and pass a blue pen to the DrawRectangle method using the same coordinates that you used to draw the red, filled rectangle. The result would be a two-colored rectangle, with a blue border and a red interior. This type of two-colored figure is natively available in the Windows API. Yet it seems apparent that few programs need to draw two-colored vector figures. That is, no doubt, a factor that contributed to the design of vector drawing in the .NET Framework and the .NET Compact Framework.

If a programmer is willing to do a bit of work, almost all vector drawing can be accomplished by calling two of these methods: DrawLine and FillPolygon. Each of the supported method names is of the form <verb><shape>. In the DrawLine method, for example, the verb is Draw and the shape is Line.

Creating Pens

Pens draw lines. The desktop supports a very sophisticated model for pens, including support for scalable geometric pens and nonscalable cosmetic pens. Pens on the desktop support features that allow you to fine-tune how an end of a line appears (rounded or squared) and even how the "elbow" joints are drawn. Pens can be wide or narrow, and even nonsolid pen colors are supported.

Wake up! In the .NET Compact Framework, pens are always 1 pixel wide. Pens provide a quick and simple way to define the color used to draw a line. From the seventeen properties supported for pens on the desktop, one has survived to the .NET Compact Framework: Color. And so it should come as no surprise that the one constructor for the Pen29 class has a single parameter, a color as shown here.

public Pen(
   Color color);

There are three ways to define a pen in a .NET Compact Framework program because there are three ways to specify a color:

  1. With a system color

  2. With a named color

  3. With an RGB value

Earlier in this chapter, we described some of the details about the three ways to pick a color. We showed that each of the color-specifying approaches could be used to create a brush. Now the time has come to show the same thing for pens.

The following code fragment creates three pens. One pen is created using a system color; another pen is created using a named color; and finally, the third pen is created with an RGB value.

// Pen from a system color
Pen penCtrl = new Pen(SystemColors.ControlDark);

// Pen from a named color
Pen penRed  = new Pen(Color.Red);

// Pen from an RGB value
Pen penBlue = new Pen(Color.FromArgb(0, 0, 255));

A Game: JaspersDots

While writing this book, we watched Paul's son, Jasper, playing a paper-and-pencil game with one of his friends. They were having so much fun that we decided to write a .NET Compact Framework version. The game was Dots, which may be familiar to some readers. In this two-person game, players take turns connecting dots that have been drawn in a grid. A player is awarded a point for drawing the last line that creates a box. We named our version of the game JaspersDots, in honor of Paul's son. The playing board for this game is drawn entirely with the following vector graphic methods:

  • FillEllipse

  • FillRectangle

  • DrawLine

  • DrawRectangle

This program provides extensive use of various Graphics objects including colors, pens, and brushes.

Figure 15.6 shows the New Game dialog box. Each player enters a name and picks a color to use for claimed squares. The default board size is 8 × 8, which can be overridden in the New Game dialog box (the maximum board size is 11 × 9).

15fig06.gifFigure 15.6 New Game dialog box for the JaspersDots program

The New Game dialog box is a simple dialog box drawn with regular controls, with one small enhancement: This dialog handles a Paint event, which draws a selection rectangle around each player's currently selected color. The set of available colors is drawn with Panel controls, five for each player. Listing 15.8 shows the source code for the event handlers for responding to the Click event for each set of Panel controls and to the Paint event for the New Game dialog box.

Example 15.8. Paint and Click Event Handlers for the New Game Dialog Box

private void
Panel1_Click(object sender, EventArgs e)
{
   if (sender == (object)panel1)
      iColor1 = 0;
   else if (sender == (object)panel2)
      iColor1 = 1;
   else if (sender == (object)panel3)
      iColor1 = 2;
   else if (sender == (object)panel4)
      iColor1 = 3;
   else if (sender == (object)panel5)
      iColor1 = 4;

   // Redraw the window.
   Invalidate();
}

private void
Panel2_Click(object sender, EventArgs e)
{
   if (sender == (object)panelA)
      iColor2 = 0;
   else if (sender == (object)panelB)
      iColor2 = 1;
   else if (sender == (object)panelC)
      iColor2 = 2;
   else if (sender == (object)panelD)
      iColor2 = 3;
   else if (sender == (object)panelE)
      iColor2 = 4;

   // Redraw the window.
   Invalidate();
}
private void
GameNewDialog_Paint(object sender, PaintEventArgs e)
{
   Panel panel = panel1;

   //
   // Player 1
   //
   // What is the current player 1 panel?
   switch(iColor1)
   {
      case 0:
         panel = panel1;
         break;
      case 1:
         panel = panel2;
         break;
      case 2:
         panel = panel3;
         break;
      case 3:
         panel = panel4;
         break;
      case 4:
         panel = panel5;
         break;
   }
   clr1 = panel.BackColor;

   // Draw a rectangle around the color selected by player 1.
   Pen penBlack = new Pen(Color.Black);
   Rectangle rc = new
      Rectangle(panel.Left - 3,
      panel.Top - 3,
      panel.Width + 5,
      panel.Height + 5);
   e.Graphics.DrawRectangle(penBlack, rc);
   rc.Inflate(1, 1);
   e.Graphics.DrawRectangle(penBlack, rc);
   rc.Inflate(1, 1);
   e.Graphics.DrawRectangle(penBlack, rc);

   //
   // Player 2
   //
   // What is the current player 2 panel?
   switch(iColor2)
   {
      case 0:
         panel = panelA;
         break;
      case 1:
         panel = panelB;
         break;
      case 2:
         panel = panelC;
         break;
      case 3:
         panel = panelD;
         break;
      case 4:
         panel = panelE;
         break;
   }
   clr2 = panel.BackColor;

   // Draw a rectangle around the color selected by player 2.
   rc = new Rectangle(panel.Left - 3,
      panel.Top - 3,
      panel.Width + 5,
      panel.Height + 5);
   e.Graphics.DrawRectangle(penBlack, rc);
   rc.Inflate(1, 1);
   e.Graphics.DrawRectangle(penBlack, rc);
   rc.Inflate(1, 1);
   e.Graphics.DrawRectangle(penBlack, rc);
}

There is a bug in Visual Studio .NET that affects C# programmers. The bug is that supported events for certain controls do not appear in the Designer. You can, however, add an event handler manually. Inside the Visual Studio code editor, you type the control name, the event name, and the += operator, and IntelliSense helps by providing the rest.

In our JaspersDots game, we found that the Designer did not support the Click event for Panel controls. To create Click event handlers for the Panel controls in the New Game dialog box, we manually typed in event handler names, which were completed for us by IntelliSense. The resulting code appears in Listing 15.9.

Example 15.9. Adding Event Handlers Manually

// Set up the Click handler for player 1 panels.
// Note: The Designer does not support this
// so we have to do it manually.
panel1.Click += new EventHandler(this.Panel1_Click);
panel2.Click += new System.EventHandler(this.Panel1_Click);
panel3.Click += new System.EventHandler(this.Panel1_Click);
panel4.Click += new System.EventHandler(this.Panel1_Click);
panel5.Click += new System.EventHandler(this.Panel1_Click);

// Set up the Click handler for player 2 panels.
// Note: The Designer does not support this
// so we have to do it manually.
panelA.Click += new EventHandler(this.Panel2_Click);
panelB.Click += new System.EventHandler(this.Panel2_Click);
panelC.Click += new System.EventHandler(this.Panel2_Click);
panelD.Click += new System.EventHandler(this.Panel2_Click);
panelE.Click += new System.EventHandler(this.Panel2_Click);

Figure 15.7 shows an example of the JaspersDots game in play. Each dot is drawn with a call to the FillEllipse method that is drawn in a bounding rectangle that is 4 pixels by 4 pixels. Players draw lines by clicking in the area between dots, and when a hit is detected a line is drawn by calling the DrawLine method. A player's claimed boxes are drawn with calls to the FillRectangle method.

15fig07.gifFigure 15.7 JaspersDots with a game under way

The JaspersDots program uses a custom control for the game window, our DotControl class. Listing 15.10 shows the source code to the DotControl class.

Example 15.10. The DotControl Class

public class DotControl : System.Windows.Forms.Control
{
   private FormMain formParent;
   private Brush m_brPlayer1;
   private Brush m_brPlayer2;
   private Squares sq;

   public DotControl(FormMain form)
   {
      formParent = form;

      formParent.Controls.Add(this);
      this.Paint += new
         PaintEventHandler(this.DotControl_Paint);
      this.MouseDown += new
         MouseEventHandler(this.DotControl_MouseDown);
      this.Left = 0;
      this.Top = 64;
      this.Width = 240;
      this.Height = 240;

      sq = new Squares(this);
   }

   public bool SetGridSize(int cxWidth, int cyHeight)
   {
      return sq.SetGridSize(cxWidth, cyHeight);
   }

   public bool SetPlayerColors(Color clr1, Color clr2)
   {
      m_brPlayer1 = new SolidBrush(clr1);
      m_brPlayer2 = new SolidBrush(clr2);

      return sq.SetPlayerBrushes(m_brPlayer1, m_brPlayer2);
   }


   private void
   DotControl_MouseDown(object sender, MouseEventArgs e)
   {
      // Check result.
      int iResult = sq.HitTest(e.X, e.Y,
         formParent.CurrentPlayer);

      // Click on the available line, no score.
      if(iResult == 1)
      {
         formParent.NextPlayer();
      }

      // Click on the available line, score.
      if (iResult == 2)
      {
         int iScore1 = sq.GetScore(1);
         formParent.DisplayScore(1, iScore1);
         int iScore2 = sq.GetScore(2);
         formParent.DisplayScore(2, iScore2);

         int count = sq.Height * sq.Width;
         if (iScore1 + iScore2 == count)
         {
            string strResult = null;

            if (iScore1 > iScore2)
               strResult = "Player 1 wins! ";
            else if (iScore1 < iScore2)
               strResult = "Player 2 wins! ";
            else
               strResult = "Tie Game! ";

            MessageBox.Show(strResult, "JaspersDots");
         }
      }
   }

   private void
   DotControl_Paint(object sender, PaintEventArgs e)
   {
      // Fill squares which players now own.
      sq.FillSquares(e.Graphics);

      // Draw lines which players have selected.
      sq.DrawLines(e.Graphics);

      // Draw dots in grid.
      sq.DrawDots(e.Graphics);
   }

} // class

The DotControl class handles two events: MouseDown and Paint. Most of the work for these events is done by a helper class named Squares. The source code for the Squares class appears in Listing 15.11.

Example 15.11. The Squares Class

public class Squares
{
   public int Width
   {
      get   { return cxWidth; }
   }
   public int Height
   {
      get   { return cyHeight; }
   }

   private int cxLeft = 15;
   private int cyTop  = 15;
   private int cxWidth;
   private int cyHeight;
   const int cxLine = 20;
   const int cyLine = 20;
   const int cxyDelta = 5;
   private Square [,] m_asq;

   private Control m_ctrlParent;
   private Brush m_brPlayer1;
   private Brush m_brPlayer2;
   private Brush m_brBackground = new _
      SolidBrush(SystemColors.Window);
   private Brush hbrBlack = new SolidBrush(Color.Black);
   private Point ptTest = new Point(0,0);
   Rectangle rc = new Rectangle(0, 0, 0, 0);
   private Size  szDot = new Size(4,4);

   Pen penLine = new Pen(Color.Black);

   public Squares(Control ctrlParent)
   {
      m_ctrlParent = ctrlParent;
   } // Squares()

   public bool SetGridSize(
      int cxNewWidth,     // Width of array.
      int cyNewHeight     // Height of array.
      )
   {
      // Temporary scratch space
      Rectangle rcTemp = new Rectangle(0,0,0,0);
      Point     ptTemp = new Point(0,0);
      Size      szTemp = new Size(0,0);

      // Set up an array to track squares.
      cxWidth = cxNewWidth;
      cyHeight = cyNewHeight;
      m_asq = new Square[cxWidth, cyHeight];
      if (m_asq == null)
         return false;

      int x, y;
      for (x = 0; x < cxWidth; x++)
      {
         for (y = 0; y < cyHeight; y++)
         {
            m_asq[x,y].iOwner = 0; // No owner.
            int xLeft = cxLeft + x * cxLine;
            int yTop = cyTop + y * cyLine;
            int xRight = cxLeft + (x+1) * cxLine;
            int yBottom = cyTop + (y+1) * cyLine;
            int cxTopBottom = cxLine - (2 * cxyDelta);
            int cyTopBottom = cxyDelta * 2;
            int cxLeftRight = cxyDelta * 2;
            int cyLeftRight = cxLine - (2 * cxyDelta);

            // Main rectangle
            ptTemp.X = xLeft + 1;
            ptTemp.Y = yTop + 1;
            szTemp.Width = xRight - xLeft - 1;
            szTemp.Height = yBottom - yTop - 1;
            rcTemp.Location = ptTemp;
            rcTemp.Size = szTemp;
            m_asq[x,y].rcMain = rcTemp;

            // Top hit rectangle
            m_asq[x,y].rcTop =
               new Rectangle(xLeft + cxyDelta,
               yTop - cxyDelta,
               cxTopBottom,
               cyTopBottom);
            m_asq[x,y].bTop = false;

            // Right hit rectangle
            m_asq[x,y].rcRight =
               new Rectangle(xRight - cxyDelta,
               yTop + cxyDelta,
               cxLeftRight,
               cyLeftRight);
            m_asq[x,y].bRight = false;

            // Bottom hit rectangle
            m_asq[x,y].rcBottom =
               new Rectangle(xLeft + cxyDelta,
               yBottom - cxyDelta,
               cxTopBottom,
               cyTopBottom);
            m_asq[x,y].bBottom = false;

            // Left hit rectangle
            m_asq[x,y].rcLeft =
               new Rectangle(xLeft - cxyDelta,
               yTop + cxyDelta,
               cxLeftRight,
               cyLeftRight);
            m_asq[x,y].bLeft = false;

         } // for y
      } // for x

      return true;
   }

   public bool
   SetPlayerBrushes(
      Brush br1,      // Brush color for player 1
      Brush br2       // Brush color for player 2
      )
   {
      m_brPlayer1 = br1;
      m_brPlayer2 = br2;

      return true;
   }

   //--------------------------------------------------------
   public void
   FillOneSquare(Graphics g, int x, int y)
   {
      Brush brCurrent = m_brBackground;
      if (m_asq[x,y].iOwner == 1)
         brCurrent = m_brPlayer1;
      else if (m_asq[x,y].iOwner == 2)
         brCurrent = m_brPlayer2;
      g.FillRectangle(brCurrent, m_asq[x,y].rcMain);
   }
   // FillSquares -- Fill owned squares with a player's color.
   //
   public void
   FillSquares(Graphics g)
   {
      int x, y;
      for (x = 0; x < cxWidth; x++)
      {
         for (y = 0; y < cyHeight; y++)
         {
            if (m_asq[x,y].iOwner != 0)
            {
               FillOneSquare(g, x, y);
            }
         }
      }
   } // method: FillSquares

   //
   // DrawOneLineSet
   //
   public void DrawOneLineSet(Graphics g, int x, int y)
   {
      int xLeft = cxLeft + x * cxLine;
      int yTop = cyTop + y * cyLine;
      int xRight = cxLeft + (x+1) * cxLine;
      int yBottom = cyTop + (y+1) * cyLine;

      if (m_asq[x,y].bTop)
         g.DrawLine(penLine, xLeft, yTop, xRight, yTop);
      if (m_asq[x,y].bRight)
         g.DrawLine(penLine, xRight, yTop, xRight, yBottom);
      if (m_asq[x,y].bBottom)
         g.DrawLine(penLine, xRight, yBottom, xLeft, yBottom);
      if (m_asq[x,y].bLeft)
         g.DrawLine(penLine, xLeft, yBottom, xLeft, yTop);
   } // DrawOneLineSet()

   //
   // DrawLines -- Draw lines which have been hit.
   //
   public void DrawLines(Graphics g)
   {
      int x, y;
      for (x = 0; x < cxWidth; x++)
      {
         for (y = 0; y < cyHeight; y++)
         {
            DrawOneLineSet(g, x, y);
         }
      }
   } // DrawLines()

   public void DrawDots (Graphics g)
   {
      // Draw array of dots.
      int x, y;
      for (x = 0; x <= cxWidth; x++)
      {
         for (y = 0; y <= cyHeight; y++)
         {
            ptTest.X = (cxLeft - 2) + x * cxLine;
            ptTest.Y = (cyTop - 2) + y * cyLine;
            rc.Location = ptTest;
            rc.Size = szDot;
            g.FillEllipse(hbrBlack, rc);
         }
      }
   } // DrawDots

   public enum Side
   {
      None,
      Left,
      Top,
      Right,
      Bottom
   }

   //
   // HitTest - Check whether a point hits a line.
   //
   // Return values:
   // 0 = miss
   // 1 = hit a line
   // 2 = hit and completed a square.
   public int HitTest(int xIn, int yIn, int iPlayer)
   {
      int x, y;
      bool bHit1 = false;
      bool bHit2 = false;
      Side sideHit = Side.None;
      for (x = 0; x < cxWidth; x++)
      {
         {         for (y = 0; y < cyHeight; y++)
            // If already owned, do not check.
            if (m_asq[x,y].iOwner != 0)
               continue;

            // Otherwise check for lines against point.
            if (m_asq[x,y].rcTop.Contains(xIn, yIn))
            {
               // Line already hit?
               if (m_asq[x,y].bTop) // Line already hit?
                  return 0;
               // If not, set line as hit.
               sideHit = Side.Top;
               m_asq[x,y].bTop = true;
            }
            else if (m_asq[x,y].rcLeft.Contains(xIn, yIn))
            {
               // Line already hit?
               if (m_asq[x,y].bLeft) // Line already hit?
                  return 0;
               // If not, set line as hit.
               sideHit = Side.Left;
               m_asq[x,y].bLeft = true;
            }
            else if (m_asq[x,y].rcRight.Contains(xIn, yIn))
            {
               // Line already hit?
               if (m_asq[x,y].bRight) // Line already hit?
                  return 0;
               // If not, set line as hit.
               sideHit = Side.Right;
               m_asq[x,y].bRight = true;
            }
            else if (m_asq[x,y].rcBottom.Contains(xIn, yIn))
            {
               // Line already hit?
               if (m_asq[x,y].bBottom) // Line already hit?
                  return 0;
               // If not, set line as hit.
               sideHit = Side.Bottom;
               m_asq[x,y].bBottom = true;
            }

            // No hit in current square -- keep looking.
            if (sideHit == Side.None)
               continue;

            // We hit a side.
            bHit1 = true;
            // Draw sides.
            Graphics g = m_ctrlParent.CreateGraphics();
            DrawOneLineSet(g, x, y);

            // Check whether square is now complete.
            // We hit a line - check for hitting a square.
            if (m_asq[x,y].bLeft &&
                  m_asq[x,y].bTop &&
                  m_asq[x,y].bRight &&
                  m_asq[x,y].bBottom)
            {
               // Side is complete.
               m_asq[x,y].iOwner = iPlayer;
               bHit2 = true;

               // Fill current square.
               FillOneSquare(g, x, y);
            }

            g.Dispose();

         } // for y
      } // for x

      if (bHit2) return 2;
      else if (bHit1) return 1;
      else return 0;

   } // HitTest

   //
   // GetScore - Get current score for player N.
   //
   public int GetScore (int iPlayer)
   {
      int iScore = 0;
      int x, y;
      for (x = 0; x < cxWidth; x++)
      {
         for (y = 0; y < cyHeight; y++)
         {
            if (m_asq[x,y].iOwner == iPlayer)
               iScore++;
         }
      }
      return iScore;
   } // GetScore

} // class Squares

Finally, we define two simple data structures—Square and Players—to hold details about individual game board squares and details about individual players, respectively. Listing 15.12 shows the code.

Example 15.12. The Square and Players Structures

   public struct Square
   {
      // Coordinate of main rectangle
      public Rectangle rcMain;
      public int iOwner;

      // Hit-rectangles of four edges of main rectangle
      public Rectangle rcTop;
      public bool bTop;
      public Rectangle rcRight;
      public bool bRight;
      public Rectangle rcBottom;
      public bool bBottom;
      public Rectangle rcLeft;
      public bool bLeft;
   } // struct Square

   public class Players
   {
      public string strName1;
      public string strName2;
      public bool bComputerPlaying;
      public System.Drawing.Color clr1;
      public System.Drawing.Color clr2;
   }
  • + Share This
  • 🔖 Save To Your Account