Drawing Shaped Forms and Windows Controls in GDI+


This article has been excerpted from book "Graphics Programming with GDI+"

Normally, all Windows controls and forms are rectangular, but what if we want to draw them in nonrectangular shapes? We can do this by setting the Region property. The Region property of a form or a control represents that window's region, which is a collection of pixels within a form or control where the operating system permits drawing; no portion of a form that lies outside of the window region is displayed. To draw nonrectangular shapes, we trick the system into drawing only the region of a control.

Let's draw a circular form. We can use the GraphicsPath class to draw graphics paths. In this application we'll create a circular form and a circular picture box, which will display an image. To test this application, we follow these simple steps:

We create a Windows application and add a button and a picture box to the form. Then we set the Text property of the button control to "Exit" and write the following line on the button click event handler:

this.Close();

Next we add a reference to the System.Drawing.Drawing2D namespace that we can use the GraphicsPath class:

using System.Drawing.Drawing2D;

On the form-load event handler, we create a Bitmap object from a file and load the bitmap in the picture box shown in the following code snippet.

Image bmp = Bitmap.FromFile("aphoto.jpg";
pictureBox1.Image = bmp;


The last step is to set the form and picture box as circular. We can modify the InitializeComponent method and add code as in Listing 15.5 at the end of the method, or we can add the code on the form-load event handler. We just set the Region property of the form and picture box to the region of our GraphicsPath object.

LISTING 15.5: Setting a form and picture box control as circular

        private void Form1_Load(object sender, System.EventArgs e)
        {
            //Create a rectangle
            Rectangle rect = new Rectangle(0, 0, 100, 100);
            //Create a graphic path
            GraphicsPath path = new GraphicsPath();
            //Add an ellipse to the graphics path
            path.AddEllipse(rect);
            //Set the Region property of the picture box
            //by creating a region form the path
            pictureBox1.Region = new Region(path);
            rect.Height += 200;
            rect.Width += 200;
            path.Reset();
            path.AddEllipse(rect);
            this.Region = new Region(path);
            //Create an image from a file and
            //set the picture box's Image property
            Image bmp = Bitmap.FromFile("aphoto.jpg");
            pictureBox1.Image = bmp;
        }



Figure 15.3.jpg
FIGURE 15.3: Drawing a circular form and Windows controls

When we build and run the application; the output will look like Figure 15.3. Because we have eliminated the normal title bar controls, we must implement an Exit button.
 
book.gif


Similar Articles