Home > Articles

This chapter is from the book

This chapter is from the book

Transforming Shapes

You now know how to create a shape by defining its vertices in Cartesian coordinates, mapping those Cartesian coordinates to screen coordinates, and then drawing lines between the vertices. But drawing a shape onscreen is only the start of the battle. Now, you must write the code needed to manipulate your shapes in various ways so that you can draw the shapes anywhere you want onscreen, as well as in any orientation. Such manipulations are called transformations. To transform a shape, you must apply some sort of formula to each vertex. You then use the new vertices to draw the shape.

Transforming Vertices, Not Lines

The fact that only the shape's vertices are transformed is an important point. Although the lines that connect the vertices actually outline a shape, those lines aren't what get transformed. By transforming every vertex in a shape, the lines automatically outline the shape properly when it gets redrawn.

Shape transformations include translation, scaling, and rotation. When you translate a shape, you move it to new Cartesian coordinates before drawing it onscreen. For example, you might want to move the shape four units to the right and two units up. When you scale a shape, you change its size. You might, for example, want to draw a triangle twice a big as the one you've defined. Finally, when you rotate a shape, you turn it to a new angle. Drawing the hands on a clock might involve this type of transformation.

Translating a Shape

Translating a shape to a new position is one of the easiest transformations you can perform. To do this, you simply add or subtract a value from each vertex's X and Y coordinate. Figure 3.6 shows a triangle being translated 3 units on the X axis and 2 units on the Y axis.

Figure 3.6Figure 3.6 Translating a triangle.

Suppose that you have the following triangle shape defined:

VERTEX triangleVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, triangleVerts};

Now, you want to translate that shape 20 units to the right and 30 units up. To do this, you add 20 to each X coordinate and 30 to each Y coordinate, giving the following vertices:

VERTEX triangleVerts[3] = {40, 80, 70, 80, 40, 130};

So the formula for translating a vertex looks like this:

x2 = x1 + xTranslation;
y2 = y1 + yTranslation;

In your program, the entire translation would look something like Listing 3.3.

Listing 3.3 Translating Shapes

VERTEX shapeVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, shapeVerts};
Translate(shape1, 20, 30);
DrawShape(shape1);

void Translate(SHAPE& shape, int xTrans, int yTrans)
{
  for (int x=0; x<shape.numVerts; ++x)
  {
    shape.vertices[x].x += xTrans;
    shape.vertices[x].y += yTrans;
  }
}

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); 
}

As you can see, the Translate() function takes as parameters a reference to a SHAPE structure, the amount of the X translation, and the amount of the Y translation. The function uses a for loop to iterate through each of the shape's vertices, adding the translation values to each X and Y coordinate. To translate in the negative direction (moving X left or Y down), you simply make xTrans or yTrans negative.

Scaling a Shape

Scaling a shape is not unlike translating a shape, except that you multiply each vertex by the scaling factor rather than add or subtract from the vertex. Figure 3.7 shows a triangle being scaled by a factor of 2.

Figure 3.7Figure 3.7 Scaling a triangle.

Suppose that you have the following triangle shape defined:

VERTEX triangleVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, triangleVerts};

Now, you want to scale the triangle by a factor of 4. To do this, you multiply each vertex's X and Y coordinates by the scaling factor of 4, giving this set of vertices:

VERTEX triangleVerts[3] = {80, 200, 200, 200, 80, 400};

So the formula for scaling a vertex looks like this:

x2 = x1 * scaleFactor;
y2 = y1 * scaleFactor;

In your program, the entire scaling would look something like Listing 3.4.

Listing 3.4 Scaling Shapes

VERTEX triangleVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, triangleVerts};
Scale(shape1, 4);
DrawShape(shape1);

void Scale(SHAPE& shape, float scaleFactor)
{
  for (int x=0; x<shape.numVerts; ++x)
  {
    shape.vertices[x].x =
      (int) (shape.vertices[x].x * scaleFactor);
    shape.vertices[x].y =
      (int) (shape.vertices[x].y * scaleFactor);
  }
}

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); 
}

A Side Effect of Scaling

Notice that the shape isn't the only thing that gets scaled. The entire coordinate system does, too. That is, a point that was two units from the origin on the X axis would be four units away after scaling by two. To avoid this side effect, you can first translate the shape to the origin (0,0), scale the shape, and then translate it back to its original location.

The Scale() function takes as parameters a reference to a SHAPE structure and the scale factor. Again, the function uses a for loop to iterate through each of the shape's vertices, this time multiplying each X and Y coordinate by the scaling factor. To scale a shape to a smaller size, use a scaling factor less than 1. For example, to reduce the size of a shape by half, use a scaling factor of 0.5. Note that, if you want, you can scale the X coordinates differently from the Y coordinates. To do this, you need both an X scaling factor and a Y scaling factor, giving you a scaling function that looks like Listing 3.5.

Listing 3.5 A Function that Scales Shapes

void Scale(SHAPE& shape, float xScale, float yScale)
{
  for (int x=0; x<shape.numVerts; ++x)
  {
    shape.vertices[x].x =
      (int) (shape.vertices[x].x * xScale);
    shape.vertices[x].y =
      (int) (shape.vertices[x].y * yScale);
  }
}

Keep in mind, though, that if you scale the X and Y coordinates differently, you'll distort the shape. Figure 3.8 shows a triangle with an X scaling factor of 1 and a Y scaling factor of 2.

Figure 3.8Figure 3.8 Scaling a triangle with different X and Y factors.

The Effect of Negative Scaling

If you scale a shape with a negative scaling factor, you create a mirror image of the shape.

Rotating a Shape

Rotating a shape is a much more complex operation than translating or scaling, because to calculate the new vertices for the rotated shape, you must resort to more sophisticated mathematics. Specifically, you must calculate sines and cosines. Luckily, as with all the math in this book, you can just plug the rotation formulas into your programs without fully understanding why they do what they do.

Figure 3.9 shows a triangle that's been rotated 45 degrees about the Cartesian origin. Notice that the entire world in which the triangle exists has been rotated, not just the shape itself. It's almost as though the triangle was drawn on a clear piece of plastic the same size as the visible part of the Cartesian plane and then the plastic was rotated 45 degrees to the left, around a pin that secures the plastic where the X and Y axes cross. This is what it means to rotate an object about the origin. If the shape is drawn at the origin, it appears as though only the shape has rotated, rather than the entire world (see Figure 3.10).

Figure 3.9Figure 3.9 Rotating a triangle.

Figure 3.10Figure 3.10  Rotating a triangle that's drawn at the origin.

Suppose that you have the following triangle shape defined:

VERTEX triangleVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, triangleVerts};

Now, you want to rotate the triangle 45 degrees. To do this, you apply the following formulas to each vertex in the triangle:

rotatedX = x * cos(angle) - y * sine(angle);
rotatedY = y * cos(angle) + x * sine(angle);

This gives you the following set of vertices:

VERTEX triangleVerts[3] = {-21, 49, 0, 70, -56, 84};

Notice that a couple of the coordinates became negative. This is because the rotation caused the triangle to rotate to the left of the Cartesian plane's X axis (see Figure 3.9). Negative values make perfectly acceptable Cartesian coordinates. However, if you were to try and draw this rotated triangle in a window, the shape would be invisible, because windows don't have negative coordinates. To make the rectangle visible, you'd have to translate it to the right, bringing the shape fully to the right of the Cartesian plane's Y axis.

In your program, the entire rotation and translation would look something like Listing 3.6.

Listing 3.6 Code for a Complete Rotation and Translation

VERTEX shapeVerts[3] = {20, 50, 50, 50, 20, 100};
SHAPE shape1 = {3, shapeVerts};
Rotate(shape1, 45);
Translate(shape1, 100, 0);
DrawShape(shape1);

void Rotate(SHAPE& shape, int degrees)
{
  int rotatedX, rotatedY;

  double radians = 6.283185308 / (360.0 / degrees);
  double c = cos(radians);
  double s = sin(radians);

  for (int x=0; x<shape.numVerts; ++x)
  {
    rotatedX =
      (int) (shape.vertices[x].x * c -
      shape.vertices[x].y * s);
    rotatedY =
      (int) (shape.vertices[x].y * c +
      shape.vertices[x].x * s);

    shape.vertices[x].x = rotatedX;
    shape.vertices[x].y = rotatedY; 
  }
}

void Translate(SHAPE& shape, int xTrans, int yTrans)
{
  for (int x=0; x<shape.numVerts; ++x)
  {
    shape.vertices[x].x += xTrans;
    shape.vertices[x].y += yTrans;
  }
}

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(hWnd, newX, newY);
  }

  LineTo(hWnd, startX, startY); 
}

The Rotate() function takes as parameters a reference to a SHAPE structure and the number of degrees to rotate the shape. The function's first task is to convert the degrees to radians. Radians are another way to measure angles and are the type of angle measurement required by Visual C++'s sin() and cos() functions. A radian is nothing more than the distance around a circle equal to the circle's radius. There are 6.283185308 (two times pi, for you math buffs) radians around a full circle. Therefore, 0 degrees equals 0 radians, 360 degrees equals 6.283185308 radians, with every other angle falling somewhere in between.

After converting the angle to radians, the function calculates the cosine and sine of the angle. Calculating these values in advance saves having to recalculate them many times within the function's for loop. Because the sin() and cos() functions tend to be slow, such recalculations can slow down things considerably (though probably not with such a simple example as this).

As with Translate() and Scale(), the Rotate() function uses a for loop to iterate through each of the shape's vertices, this time recalculating each X and Y using the rotation formula.

Direction of Rotation

Positive angles cause the shape to rotate counterclockwise. To rotate a shape clockwise, use negative values for the degrees parameter.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020