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 DrawRetangle 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 Pen [29] class has a single parameter, a color as shown here.
Public Sub New( _ ByVal color as Color)
There are three ways to define a pen in a .NET Compact Framework program because there are three ways to specify a color:
-
With a system color
-
With a named color
-
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 Dim penCtrl As Pen = New Pen(SystemColors.ControlDark) ' Pen from a named color Dim penRed As Pen = New Pen(Color.Red) ' Pen from an RGB value Dim penBlue As Pen = 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).
Figure 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 Sub panel1_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles panel1.Click, panel2.Click, _ panel3.Click, panel4.Click, panel5.Click If sender Is panel1 Then iColor1 = 0 ElseIf sender Is panel2 Then iColor1 = 1 ElseIf sender Is panel3 Then iColor1 = 2 ElseIf sender Is panel4 Then iColor1 = 3 ElseIf sender Is panel5 Then iColor1 = 4 End If ' Redraw the window. Invalidate() End Sub Private Sub panel2_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles panelA.Click, panelB.Click, _ panelC.Click, panelD.Click, panelE.Click If sender Is panelA Then iColor2 = 0 ElseIf sender Is panelB Then iColor2 = 1 ElseIf sender Is panelC Then iColor2 = 2 ElseIf sender Is panelD Then iColor2 = 3 ElseIf sender Is panelE Then iColor2 = 4 End If ' Redraw the window. Invalidate() End Sub Private Sub GameNewDialog_Paint( _ ByVal sender As Object, _ ByVal e As PaintEventArgs) Handles MyBase.Paint Dim panel As Panel = panel1 ' ' Player 1 ' ' What is the current player 1 panel? Select Case iColor1 Case 0 panel = panel1 Case 1 panel = panel2 Case 2 panel = panel3 Case 3 panel = panel4 Case 4 panel = panel5 End Select clr1 = panel.BackColor ' Draw a rectangle around the color selected by player 1. Dim penBlack As Pen = New Pen(Color.Black) Dim rc As Rectangle = 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? Select Case iColor2 Case 0 panel = panelA Case 1 panel = panelB Case 2 panel = panelC Case 3 panel = panelD Case 4 panel = panelE End Select 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) End Sub
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.
Figure 15.7 JaspersDots with a game under way
The JaspersDots program uses a custom control for the game window, our DotControl class. Listing 15.9 shows the source code to the DotControl class.
Example 15.9. The DotControl Class
Public Class DotControl Inherits System.Windows.Forms.Control Private formParent As FormMain Private m_brPlayer1 As Brush Private m_brPlayer2 As Brush Private sq As Squares Sub New(ByVal form As FormMain) formParent = form formParent.Controls.Add(Me) Me.Left = 0 Me.Top = 64 Me.Width = 240 Me.Height = 240 sq = New Squares(Me) End Sub Public Function SetGridSize( _ ByVal cxWidth As Integer, _ ByVal cyHeight As Integer) As Boolean Return sq.SetGridSize(cxWidth, cyHeight) End Function Public Function SetPlayerColors( _ ByVal clr1 As Color, _ ByVal clr2 As Color) As Boolean m_brPlayer1 = New SolidBrush(clr1) m_brPlayer2 = New SolidBrush(clr2) Return sq.SetPlayerBrushes(m_brPlayer1, m_brPlayer2) End Function Private Sub DotControl_MouseDown( _ ByVal sender As Object, _ ByVal e As MouseEventArgs) Handles MyBase.MouseDown ' Check the result. Dim iResult As Integer = sq.HitTest(e.X, e.Y, _ formParent.CurrentPlayer) ' Click on the available line, no score. If iResult = 1 Then formParent.NextPlayer() End If ' Click on the available line, score. If iResult = 2 Then Dim iScore1 As Integer = sq.GetScore(1) formParent.DisplayScore(1, iScore1) Dim iScore2 As Integer = sq.GetScore(2) formParent.DisplayScore(2, iScore2) Dim count As Integer = sq.Height * sq.Width If iScore1 + iScore2 = count Then Dim strResult As String = Nothing If iScore1 > iScore2 Then strResult = "Player 1 wins! " ElseIf iScore1 < iScore2 Then strResult = "Player 2 wins! " Else strResult = "Tie Game! " End If MessageBox.Show(strResult, "JaspersDots") End If End If End Sub Private Sub DotControl_Paint( _ ByVal sender As Object, _ ByVal e As PaintEventArgs) Handles MyBase.Paint ' Fill squares that players now own. sq.FillSquares(e.Graphics) ' Draw lines that players have selected. sq.DrawLines(e.Graphics) ' Draw dots in the grid. sq.DrawDots(e.Graphics) End Sub End 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.10.
Example 15.10. The Squares Class
Public Class Squares Public ReadOnly Property Width() As Integer Get Return cxWidth End Get End Property Public ReadOnly Property Height() As Integer Get Return cyHeight End Get End Property Private cxLeft As Integer = 15 Private cyTop As Integer = 15 Private cxWidth As Integer Private cyHeight As Integer Const cxLine As Integer = 20 Const cyLine As Integer = 20 Const cxyDelta As Integer = 5 Private m_asq(,) As Square Private m_ctrlParent As Control Private m_brPlayer1 As Brush Private m_brPlayer2 As Brush Private m_brBackground As Brush = _ New SolidBrush(SystemColors.Window) Private hbrBlack As Brush = New SolidBrush(Color.Black) Private ptTest As Point = New Point(0, 0) Dim rc As Rectangle = New Rectangle(0, 0, 0, 0) Private szDot As Size = New Size(4, 4) Dim penLine As Pen = New Pen(Color.Black) Public Sub New(ByVal ctrlParent As Control) m_ctrlParent = ctrlParent End Sub Public Function SetGridSize( _ ByVal cxNewWidth As Integer, _ ByVal cyNewHeight As Integer) As Boolean ' Temporary scratch space. Dim rcTemp As Rectangle = New Rectangle(0, 0, 0, 0) Dim ptTemp As Point = New Point(0, 0) Dim szTemp As Size = New Size(0, 0) ' Set up an array to track squares. cxWidth = cxNewWidth cyHeight = cyNewHeight m_asq = New Square(cxWidth, cyHeight) {} If m_asq Is Nothing Then Return False End If Dim x As Integer, y As Integer For x = 0 To cxWidth - 1 For y = 0 To cyHeight - 1 m_asq(x, y).iOwner = 0 ' No owner. Dim xLeft As Integer = cxLeft + x * cxLine Dim yTop As Integer = cyTop + y * cyLine Dim xRight As Integer = cxLeft + (x + 1) * cxLine Dim yBottom As Integer = cyTop + (y + 1) * cyLine Dim cxTopBottom As Integer = cxLine - (2 * cxyDelta) Dim cyTopBottom As Integer = cxyDelta * 2 Dim cxLeftRight As Integer = cxyDelta * 2 Dim cyLeftRight As Integer = 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 Next y Next x Return True End Function Public Function _ SetPlayerBrushes( _ ByVal br1 As Brush, _ ByVal br2 As Brush) m_brPlayer1 = br1 m_brPlayer2 = br2 Return True End Function Public Sub FillOneSquare( _ ByVal g As Graphics, _ ByVal x As Integer, _ ByVal y As Integer) Dim brCurrent As Brush = m_brBackground If m_asq(x, y).iOwner = 1 Then brCurrent = m_brPlayer1 ElseIf m_asq(x, y).iOwner = 2 Then brCurrent = m_brPlayer2 End If g.FillRectangle(brCurrent, m_asq(x, y).rcMain) End Sub ' FillSquares -- Fill owned squares with a player's color. Public Sub FillSquares(ByVal g As Graphics) Dim x As Integer, y As Integer For x = 0 To cxWidth - 1 For y = 0 To cyHeight - 1 If m_asq(x, y).iOwner <> 0 Then FillOneSquare(g, x, y) End If Next Next End Sub ' FillSquares() ' DrawOneLineSet ' Public Sub DrawOneLineSet( _ ByVal g As Graphics, _ ByVal x As Integer, _ ByVal y As Integer) Dim xLeft As Integer = cxLeft + x * cxLine Dim yTop As Integer = cyTop + y * cyLine Dim xRight As Integer = cxLeft + (x + 1) * cxLine Dim yBottom As Integer = cyTop + (y + 1) * cyLine If (m_asq(x, y).bTop) Then g.DrawLine(penLine, xLeft, yTop, xRight, yTop) End If If (m_asq(x, y).bRight) Then g.DrawLine(penLine, xRight, yTop, xRight, yBottom) End If If (m_asq(x, y).bBottom) Then g.DrawLine(penLine, xRight, yBottom, xLeft, yBottom) End If If (m_asq(x, y).bLeft) Then g.DrawLine(penLine, xLeft, yBottom, xLeft, yTop) End If End Sub ' DrawOneLineSet() ' DrawLines -- Draw lines that have been hit. ' Public Sub DrawLines(ByVal g As Graphics) Dim x As Integer, y As Integer For x = 0 To cxWidth - 1 For y = 0 To cyHeight - 1 DrawOneLineSet(g, x, y) Next Next End Sub Public Sub DrawDots(ByVal g As Graphics) ' Draw an array of dots. Dim x As Integer, y As Integer For x = 0 To cxWidth For y = 0 To cyHeight ptTest.X = (cxLeft - 2) + x * cxLine ptTest.Y = (cyTop - 2) + y * cyLine rc.Location = ptTest rc.Size = szDot g.FillEllipse(hbrBlack, rc) Next Next End Sub ' DrawDots Public Enum Side None Left Top Right Bottom End Enum ' HitTest - Check whether a point hits a line. ' ' Return values: ' 0 = miss. ' 1 = hit a line. ' 2 = hit and completed a square. Public Function HitTest( _ ByVal xIn As Integer, _ ByVal yIn As Integer, _ ByVal iPlayer As Integer) As Integer Dim x As Integer, y As Integer Dim bHit1 As Boolean = False Dim bHit2 As Boolean = False Dim sideHit As Side = Side.None For x = 0 To cxWidth - 1 For y = 0 To cyHeight - 1 ' If already owned, do not check If m_asq(x, y).iOwner = 0 Then ' Check for lines against point. If m_asq(x, y).rcTop.Contains(xIn, yIn) Then ' Line already hit? If m_asq(x, y).bTop Then Return 0 End If ' If not, set line as hit. sideHit = Side.Top m_asq(x, y).bTop = True ElseIf m_asq(x, y).rcLeft.Contains(xIn, yIn) Then ' Line already hit? If m_asq(x, y).bLeft Then Return 0 End If ' If not, set line as hit. sideHit = Side.Left m_asq(x, y).bLeft = True ElseIf m_asq(x, y).rcRight.Contains(xIn, yIn) Then ' Line already hit? If m_asq(x, y).bRight Then Return 0 End If ' If not, set line as hit. sideHit = Side.Right m_asq(x, y).bRight = True ElseIf m_asq(x, y).rcBottom.Contains(xIn, yIn) Then ' Line already hit? If m_asq(x, y).bBottom Then Return 0 End If sideHit = Side.Bottom ' If not, set line as hit. m_asq(x, y).bBottom = True End If If (sideHit <> Side.None) Then ' We hit a side. bHit1 = True ' Draw sides. Dim g As Graphics = _ m_ctrlParent.CreateGraphics() DrawOneLineSet(g, x, y) ' Check whether the square is now complete. ' We hit a line - check for hitting a square. If (m_asq(x, y).bLeft And _ m_asq(x, y).bTop And _ m_asq(x, y).bRight And _ m_asq(x, y).bBottom) Then ' Side is complete. m_asq(x, y).iOwner = iPlayer bHit2 = True ' Fill the current square. FillOneSquare(g, x, y) End If g.Dispose() End If End If Next y Next x If (bHit2) Then Return 2 ElseIf (bHit1) Then Return 1 Else Return 0 End If End Function ' GetScore - Get the current score for player N. ' Public Function GetScore( _ ByVal iPlayer As Integer) As Integer Dim iScore As Integer = 0 Dim x As Integer, y As Integer For x = 0 To cxWidth - 1 For y = 0 To cyHeight - 1 If m_asq(x, y).iOwner = iPlayer Then iScore = iScore + 1 End If Next Next Return iScore End Function ' GetScore End Class
Finally, we define two simple data structuresSquare and Playersto hold details about individual game board squares and details about individual players, respectively. Listing 15.11 shows the code.
Example 15.11. The Square and Players Structures
Public Structure Square ' Coordinate of main rectangle Public rcMain As Rectangle Public iOwner As Integer ' Hit-rectangles of four edges of main rectangle Public rcTop As Rectangle Public bTop As Boolean Public rcRight As Rectangle Public bRight As Boolean Public rcBottom As Rectangle Public bBottom As Boolean Public rcLeft As Rectangle Public bLeft As Boolean End Structure Public Class Players Public strName1 As String Public strName2 As String Public bComputerPlaying As Boolean Public clr1 As System.Drawing.Color Public clr2 As System.Drawing.Color End Class