Home > Articles

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

This chapter is from the book

Defining Vertex and Shape Data Types

As you learned in the previous section, 2D shapes are defined by a set of points, called vertices. Each vertex is connected to the next by a line. When all of the vertices are connected, the shape is finished. To make handling various types of shapes in a program easier, you need to define a couple of new data types. The first data type is for a vertex, and it looks like this:

typedef struct vertex
{
  int x, y;
} VERTEX;

This structure simply holds the X and Y Cartesian coordinates of a vertex.

The next data type defines a complete shape, like this:

typedef struct shape
{
  int numVerts;
  VERTEX* vertices;
} SHAPE;

This structure contains an integer to hold the number of vertices in the shape and a pointer to an array of VERTEX structures.

By using these new data types, you can write a more generalized version of the shape-drawing code, placing the loop and the variables on which it depends into its own function. That program code would look something like Listing 3.2.

Listing 3.2 Drawing Shapes from Generalized Data

VERTEX triangleVerts[3] = {2, 5, 5, 2, 2, 2};
SHAPE shape1 = {3, triangleVerts};
DrawShape(shape1);

void DrawShape(SHAPE& shape1)
{
  int newX, newY, startX, startY;
  RECT clientRect;
  GetClientRect(hWnd, &clientRect);
  int maxY = clientRect.bottom;

  for (int x=0; x<shape1.numVerts; ++x)
  {
    newX = shape1.vertices[x].x;
    newY = maxY - shape1.vertices[x].y;
    if (x == 0)
    {
      MoveToEx(hDC, newX, newY, 0);
      startX = newX;
      startY = newY; 
    }
    else
      LineTo(hDC, newX, newY);
  }

  LineTo(hDC, startX, startY); 
}

Because the DrawShape() function has been generalized to work with SHAPE structures, the function can draw any type of shape you want to define. For example, to draw a rectangle, you might define shape1 like this:

VERTEX rectangleVerts[4] = {10, 10, 100, 10, 100, 50, 10, 50};
SHAPE shape1 = {4, rectangleVerts};

In fact, the shapes you define can be as fancy as you want. The shape defined in the following code is shown in Figure 3.5:

VERTEX shapeVerts[6] =
  {10, 10, 75, 5, 100, 20, 100, 50, 50, 50, 50, 25};
SHAPE shape1 = {6, shapeVerts};

Figure 3.5Figure 3.5 The SHAPE structure lets you define many types of shapes.

  • + Share This
  • 🔖 Save To Your Account