This article has been excerpted from book "Graphics Programming with GDI+".In this article we create an application, GDI+Painter that you can use to draw and fill simple graphics objects. If you wish, you can add more functionality to the application. Once you are done graphics shapes, the program allows you to save your drawing in bitmap format. You can modify the program to save a drawing in .jpeg or .gif format.The program is a Windows Forms application and looks like Figure 3.42. It has three draw buttons (line, ellipse, and rectangle) and two fill buttons (rectangle and ellipse). The Save Image button allows you to save the image.Click on a button and the program draws the selected item on the form.Here's how it works:First we define some private class-level variables: //Variables private Bitmap bitmap = null; private Bitmap curBitmap = null; private bool dragMode = false; private int drawIndex = 1; private int curX, curY, x, y; private int diffX, diffY; private Graphics curGraphics; private Pen curPen; private SolidBrush curBrush; private Size fullSize;The next step is to initialize objects. On the form-load event handler, we create a bitmap and a Graphics object from the bitmap, which represents the entire form. We set its background color to the form's background color by calling the Graphics.Clear method. We also create a Pen object and a Brush object when the form loads. Listing 3.31 gives the form-load event handler code.Listing 3.31: The form-load event handlerprivate void Form1_Load(object sender, System.EventArgs e) { // Get the full size of the form fullSize = SystemInformation.PrimaryMonitorMaximizedWindowSize ; // Create a bitmap using full size Bitmap = new Bitmap (fullSize.Width, fullSize.Height); // Create a Graphics object from Bitmap curGraphics = Graphics.FromImage(bitmap); // Set backgound color as form's color curGraphics.Clear (this.BackColor); // Create a new pen and brush as // default pen and brush curPen = new Pen (Color.Black); curBrush = new SolidBrush(Color.Black); }When we click on a button, we find out which button was selected and save it in the drawIndex variable. Listing 3.32 gives code for the button click event handler for all buttons.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: