Home > Articles

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

This chapter is from the book

Building a 2D Graphics Application

You now have all the information you need to write a 2D graphics program that can draw various shapes as well as translate, scale, and rotate those shapes. In Chapter 2, "Writing a Windows Program," you learned how to write C++ Windows programs that don't rely on the Microsoft Foundation Classes, and for the Direct3D programs you'll develop later in this book, you will use those programming techniques. However, you develop the programs in this chapter and in Chapter 4, "Programming 3D Computer Graphics," using Visual Studio's application wizards and MFC. Perform the steps in the following sections to create a program called Graphics2D that demonstrates the principles you learned in this chapter.

Creating the Basic Project

In the first set of steps that follow, you create the basic project and modify the application's user interface. (The following steps assume that you have experience with using Visual C++ to write Windows applications. If you don't know how to perform any of the following steps, consult your Visual C++ documentation.)

  1. Create a new MFC application named Graphics2D, as shown in Figure 3.13.

Figure 3.13Figure 3.13  Creating the Graphics2D project.

  1. In the MFC Application Wizard dialog box, click the Application Type selection. Then set the Application Type option to Single Document and the Use of MFC option to Use MFC in a Static Library, as shown in Figure 3.14.

Figure 3.14Figure 3.14 The Application Type options.

  1. Click the User Interface Features selection. Then turn off the Initial Status Bar option, as shown in Figure 3.15.

Figure 3.15Figure 3.15 The User Interface Features options.

  1. Again in the MFC Application Wizard dialog box, click the Advanced Features selection. Then turn off the Printing and Print Preview and ActiveX Controls options, as shown in Figure 3.16.

Figure 3.16Figure 3.16 The Advanced Features options.

  1. Click Finish to generate the project's source code files.

Editing the Project's Resources

Next, you modify the application's resources, including menus and dialog boxes. Perform the following steps to get your program's resources ready to go:

  1. Double-click the Graphics2D.rc file in the Solution Explorer to bring up the Resource View pane.

  2. Double-click the Menu folder, and then double-click IDR_MAINFRAME to bring up the menu editor (see Figure 3.17).

Figure 3.17Figure 3.17 The menu editor.

  1. Delete all entries from the File menu except Exit (see Figure 3.18).

Figure 3.18Figure 3.18 The new File menu.

  1. Delete the Edit and View menus, leaving the File and Help menus, as shown in Figure 3.19.

Figure 3.19Figure 3.19 The menu bar after deleting the Edit menu.

  1. Add a Transform menu, giving it the commands Translate, Scale, and Rotate (see Figure 3.20).

Figure 3.20Figure 3.20 The new Transform menu.

  1. Close the menu editor and bring up the dialog box editor (see Figure 3.21) by double-clicking the Dialog folder in the Resource View pane and then double-clicking IDD_ABOUTBOX.

Figure 3.21Figure 3.21 The dialog editor.

  1. Modify the About dialog box so that it looks like Figure 3.22.

Figure 3.22Figure 3.22 The new About dialog box.

  1. Close the dialog box editor and double-click Accelerator in the Resource View pane. You'll see the IDR_MAINFRAME accelerator ID (see Figure 3.23). Delete the IDR_MAINFRAME accelerator table from the browser window.

Figure 3.23Figure 3.23 The IDR_MAINFRAME accelerator table.

  1. Select the Project menu's Add Resource command, and create a new dialog box. The finished dialog box should look like Figure 3.24. (Be sure to give the dialog box the IDD_TRANSFORM ID, and give the edit controls the IDs IDC_XAXIS and IDC_YAXIS.)

Figure 3.24Figure 3.24 The Transform dialog box.

  1. Double-click the dialog box to bring up the MFC Class Wizard dialog box. Name the Transform dialog box's class CTransformDlg and set the Base Class type to CDialog (see Figure 3.25). Click Finish to create the class.

Figure 3.25Figure 3.25 Creating the CTransformDlg class.

  1. Switch to the Class View pane and then right-click the CTransformDlg class. Select the Add/Add Variable command from the menu that appears. Use this command to add public variables called m_xAxis and m_yAxis of type double. Associate these variables with the edit controls, as shown in Figure 3.26.

Figure 3.26Figure 3.26 Creating a variable for one of the edit controls.

  1. Press Ctrl+Shift+S to save all your changes.

Creating Message-Response Functions

In the next set of steps, you add message-response functions for the commands in the Transform menu and for the WM_RBUTTONDOWN Windows message.

  1. In the Class View pane, click on the CGraphics2DView class. In the class's Properties window, click the Events button (the one that looks like a lightning bolt) to display the many events to which the class can respond.

  2. Add COMMAND functions for the ID_TRANSFORM_ROTATE, ID_TRANSFORM_SCALE, and ID_TRANSFORM_TRANSLATE commands. Stick with the default names of OnTransformRotate(), OnTransformScale(), and OnTransformTranslate(), as shown in Figure 3.27.

Figure 3.27Figure 3.27 Adding response functions for the Transform menu commands.

  1. Find the OnTransformRotate() function at the end of the Graphics2DView.cpp file, and add Listing 3.16 to that function, right after the // TODO: Add your command handler code here comment.

Listing 3.16 New Code for OnTransformRotate()

CTransformDlg dlg;
dlg.m_xAxis = 0;
dlg.m_yAxis = 0;

INT_PTR response = dlg.DoModal();

if (response == IDOK)
  m_rotate = (int) dlg.m_xAxis;
  1. Find the OnTransformScale() function at the end of the Graphics2DView.cpp file, and add Listing 3.17 to that function, right after the // TODO: Add your command handler code here comment.

Listing 3.17 New Code for OnTransformScale()

CTransformDlg dlg;
dlg.m_xAxis = 1;
dlg.m_yAxis = 1;

INT_PTR response = dlg.DoModal();

if (response == IDOK)
{
  m_xScale = dlg.m_xAxis;
  m_yScale = dlg.m_yAxis;
}
  1. Find the OnTransformTranslate() function at the end of the Graphics2DView.cpp file, and add Listing 3.18 to that function, right after the // TODO: Add your command handler code here comment.

Listing 3.18 New Code for OnTransformTranslate()

CTransformDlg dlg;
dlg.m_xAxis = 0;
dlg.m_yAxis = 0;

INT_PTR response = dlg.DoModal();

if (response == IDOK)
{
  m_xTranslate = dlg.m_xAxis;
  m_yTranslate = dlg.m_yAxis; 
}
  1. In the class's Properties window, click the Messages button (the one to the right of the lightning bolt) to display the many Windows messages to which the class can respond.

  2. Create a response function named OnRButtonDown() for the WM_RBUTTONDOWN message, as shown in Figure 3.28.

Figure 3.28Figure 3.28 Adding the OnRButtonDown() function.

  1. Add Listing 3.19 to the OnRButtonDown() function, right after the // TODO: Add your message handler code here and/or call default comment.

Listing 3.19 New Code for OnRButtonDown()

MATRIX3X3 m;
InitMatrix(m);

Translate(m, (int) m_xTranslate, (int) m_yTranslate);
Scale(m, m_xScale, m_yScale);
Rotate(m, m_rotate);
Transform(m_polygon, m);

m_rotate = 0;
m_xScale = 1;
m_yScale = 1;
m_xTranslate = 0;
m_yTranslate = 0;

Invalidate(TRUE); 

Finishing the View Class

In the next set of steps, you add the source code that completes the CGraphics2DView class. You also add the required member function and data member declarations to the CGraphics2DView class's header file. Perform the following steps to complete these tasks:

  1. Add the following lines near the top of the Graphics2DView.cpp file, right after the #endif compiler directive:

    #include <math.h>
    #include "TransformDlg.h"
  2. Add Listing 3.20 to the CGraphics2DView class's constructor, right after the // TODO: add construction code here comment.

Listing 3.20 New Code for CGraphics2DView Constructor

m_polygon.numVerts = 4;
m_polygon.vertices = m_vectors;
m_vectors[0].x = 0;
m_vectors[0].y = 0;
m_vectors[0].w = 1;
m_vectors[1].x = 100;
m_vectors[1].y = 0;
m_vectors[1].w = 1;
m_vectors[2].x = 100;
m_vectors[2].y = 50;
m_vectors[2].w = 1;
m_vectors[3].x = 0;
m_vectors[3].y = 75;
m_vectors[3].w = 1;

m_rotate = 0;
m_xScale = 1;
m_yScale = 1;
m_xTranslate = 0;
m_yTranslate = 0;
  1. Add the following line to the CGraphics2DView class's OnDraw() function, right after the // TODO: add draw code for native data here comment:

    DrawShape(pDC, m_polygon);
  2. Again in OnDraw(), uncomment the pDC parameter.

  3. Also in Graphics2DView.cpp, add the functions in Listing 3.21 to the end of the file. Note that because this is an MFC program, Windows API functions such as MoveToEx() and LineTo() have been replaced with their MFC counterparts, but their functionality is the same.

Listing 3.21 New Functions for the CGraphics2DView Class

void CGraphics2DView::InitMatrix(MATRIX3X3& m)
{
  m[0][0]=1; m[0][1]=0; m[0][2]=0;
  m[1][0]=0; m[1][1]=1; m[1][2]=0;
  m[2][0]=0; m[2][1]=0; m[2][2]=1;
}

void CGraphics2DView::CopyMatrix(MATRIX3X3& dst, MATRIX3X3& src)
{
  for (int i=0; i<3; ++i)
   for (int j=0; j<3; ++j)
     dst[i][j] = src[i][j];
}

void CGraphics2DView::MultMatrix(MATRIX3X3& product,
   MATRIX3X3& matrix1, MATRIX3X3& matrix2)
{
  for (int x=0; x<3; ++x)
    for (int y=0; y<3; ++y)
    {
      double sum = 0;
      for (int z=0; z<3; ++z)
        sum += matrix1[x][z] * matrix2[z][y];
      product[x][y] = sum;
    }
}

void CGraphics2DView::Translate(MATRIX3X3& m, int xTrans, int yTrans)
{
  MATRIX3X3 m1, m2;

  m1[0][0]=1;    m1[0][1]=0;    m1[0][2]=0;
  m1[1][0]=0;    m1[1][1]=1;    m1[1][2]=0;
  m1[2][0]=xTrans; m1[2][1]=yTrans; m1[2][2]=1;

  MultMatrix(m2, m1, m);
  CopyMatrix(m, m2);
}

void CGraphics2DView::Scale(MATRIX3X3& m, double xScale, double yScale)
{
  MATRIX3X3 m1, m2;

  m1[0][0]=xScale; m1[0][1]=0;   m1[0][2]=0;
  m1[1][0]=0;   m1[1][1]=yScale; m1[1][2]=0;
  m1[2][0]=0;   m1[2][1]=0;   m1[2][2]=1;

  MultMatrix(m2, m1, m);
  CopyMatrix(m, m2);
}

void CGraphics2DView::Rotate(MATRIX3X3& m, int degrees)
{
  MATRIX3X3 m1, m2;

  if (degrees == 0) return;

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

  m1[0][0]=c; m1[0][1]=s; m1[0][2]=0;
  m1[1][0]=-s; m1[1][1]=c; m1[1][2]=0;
  m1[2][0]=0; m1[2][1]=0; m1[2][2]=1;
  
  MultMatrix(m2, m1, m);
  CopyMatrix(m, m2);
}

void CGraphics2DView::Transform(SHAPE& shape, MATRIX3X3& m)
{
  int transformedX, transformedY;

  for (int x=0; x<shape.numVerts; ++x)
  {
    transformedX = (int) (shape.vertices[x].x * m[0][0] +
      shape.vertices[x].y * m[1][0] + m[2][0]);
    transformedY = (int) (shape.vertices[x].x * m[0][1] +
      shape.vertices[x].y * m[1][1] + m[2][1]);
    shape.vertices[x].x = transformedX;
    shape.vertices[x].y = transformedY;
  }
}

void CGraphics2DView::DrawShape(CDC* pDC, SHAPE& shape1)
{
  int newX, newY, startX, startY;
  RECT clientRect;

  GetClientRect(&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)
    {
      pDC->MoveTo(newX, newY);
      startX = newX;
      startY = newY;
    }
    else
      pDC->LineTo(newX, newY);
  }

  pDC->LineTo(startX, startY);
}
  1. Load Graphics2DView.h and add Listing 3.22 to the top of the file, right before the CGraphics2DView class declaration.

Listing 3.22 New Code for the CGraphics2DView Class's Header File

typedef double MATRIX3X3[3][3];

typedef struct vector
{
  int x, y, w;
} VECTOR;

typedef struct shape
{
  int numVerts;
  VECTOR* vertices;
} SHAPE;
  1. Also in Graphics2DView.h, add Listing 3.23 to the CGraphics2DView class's Attributes section, right after the CGraphics2DDoc* GetDocument() const line.

Listing 3.23 New Code for the CGraphics2DView Class's Attributes Section

protected:
  SHAPE m_polygon;
  VECTOR m_vectors[4];
  int m_rotate;
  double m_xScale, m_yScale;
  double m_xTranslate, m_yTranslate;
  1. Again in Graphics2DView.h, add Listing 3.24 to the CGraphics2DView class's Implementation section, right after the protected keyword.

Listing 3.24 New Code for the CGraphics2DView Class's Implementation Section

void DrawShape(CDC* pDC, SHAPE& shape1);
void Translate(MATRIX3X3& m, int xTrans, int yTrans);
void Scale(MATRIX3X3& m, double xScale, double yScale);
void Rotate(MATRIX3X3& m, int degrees);
void Transform(SHAPE& shape, MATRIX3X3& m);
void MultMatrix(MATRIX3X3& product,
  MATRIX3X3& matrix1, MATRIX3X3& matrix2);
void InitMatrix(MATRIX3X3& m);
void CopyMatrix(MATRIX3X3& dst, MATRIX3X3& src);

Your Graphics2D program is now complete. To create the application, press Ctrl+Shift+B. To run the application, press F5 on your keyboard.

  • + Share This
  • 🔖 Save To Your Account

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