- Drawing Graphics
- Working with Images
- Formatting Text
The System.Drawing namespace provides tools for drawing graphics and editing existing images. The most useful classes are Graphics, Image, and Bitmap.
Use the Point and Size classes to specify the location and size of controls.
The System.Drawing.Color structure provides predefined properties for common colors.
To draw lines and shapes, create an instance of the Graphics class, create a Pen object, and then call one of the Graphics member methods to draw a line or a shape using the Pen instance.
Pens can be customized by adding endcaps or changing the line pattern to various combinations of dots and dashes.
To draw solid shapes, create an instance of the Graphics class, create a Brush object, and then call one of the Graphics member methods to draw the shape using the Brush instance.
To draw lines and curves, create two objects: a Pen object and a Graphics object. Use the Pen object to define the color and width of the drawing. The Graphics object exposes methods for drawing lines and shapes. To fill in shapes, use a Brush object with a Graphics object.
Working with Images
The Image and Bitmap classes enable you to edit or create pictures and save the results as a file.
To display a picture in a Windows Forms window, load the picture into an instance of the Image or Bitmap class, create an instance of the PictureBox control, and then use the Image or Bitmap object to define the PictureBox.BackgroundImage property.
The Image class is abstract, but you can create instances of the class using the Image.FromFile method (which accepts a path to an image file as a parameter) and the Image.FromStream method (which accepts a System.IO.Stream object as a parameter).
Bitmap is the most commonly used class for working with new or existing images. The different constructors allow you to create a Bitmap from an existing Image, file, or stream, or to create a blank bitmap of a specified height and width.
To create and save a picture, create a Bitmap object, edit it using a Graphics object, and then call the Bitmap.Save method.
To display an icon, call the Graphics.DrawIcon or Graphics.DrawIconUnstretched methods using one of the properties of the SystemIcons class.
To add text to graphics, create a Graphics object, create a Font object, create a Brush object if you want, and then call the Graphics.DrawString method.
To create a Font object, pass the font family name, font size, and font style to the constructor.
Write text by calling the Graphics.DrawString method. The DrawString method requires a Font object, a Brush object that specifies the color of the text, and the location to draw the text.
Use the StringFormat class to control the formatting of text. You can use this class to change the direction of the text, or to change the alignment of text.