Graphics and Multimedia

  • In this article you will learn:

    • To understand graphics contexts and graphics objects
    • To manipulate colors and fonts
    • To understand and use GDI+ Graphics methods to draw lines, rectangles, strings and images
    • To use class Image to manipulate and display images
    • To draw complex shapes from simple shapes with class GraphicsPath
    • To use Windows Media Player to play audio or video in a C# application
    • To use Microsoft Agent to add interactive animated characters to a C# application
  • In this article, we overview C#’s tools for drawing two-dimensional shapes and for controlling colors and fonts. C# supports graphics that enable programmers to enhance their Windows applications visually. The FCL contains many sophisticated drawing capabilities as part of namespace System.Drawing and the other namespaces that make up the .NET resource GDI+. GDI+ is an application programming interface (API) that provides classes for creating two-dimensional vector graphics (a way to describe graphics so that they may be easily manipulated with high-performance techniques), manipulating fonts and inserting images
  • We begin with an introduction to the .NET framework’s drawing capabilities. We then present more powerful drawing capabilities, such as changing the styles of lines used to draw shapes and controlling the colors and patterns of filled shapes
  • Drawing Classes and the Coordinate System:

    • depicts a portion of namespace System.Drawing, including several graphics classes and structures covered in this chapter. Namespaces System.Drawing and System.Drawing.Drawing2D contain the most commonly used GDI+ components
  • Class Graphics contains methods used for drawing strings, lines, rectangles and other shapes on a Control. The drawing methods of class Graphics usually require a Pen or Brush object to render a specified shape. The Pen draws shape outlines; the Brush draws solid objects
  • The Color structure contains numerous static properties, which set the colors of various graphical components, plus methods that allow users to create new colors. Class Font contains properties that define unique fonts. Class FontFamily contains methods for obtaining font information
  • To begin drawing in C#, we first must understand GDI+’s coordinate system, a scheme for identifying every point on the screen. By default, the upper-left corner of a GUI component (such as a Panel or a Form) has the coordinates (0, 0). A coordinate pair has both an x-coordinate (the horizontal coordinate) and a y-coordinate (the vertical coordinate). The x-coordinate is the horizontal distance (to the right) from the upper-left corner. The y-coordinate is the vertical distance (downward) from the upper left corner. The x-axis defines every horizontal coordinate, and the y-axis defines every vertical coordinate. Programmer’s position text and shapes on the screen by specifying their (x, y) coordinates. Coordinate units are measured in pixels ("picture elements"), which are the smallest units of resolution on a display monitor
  • Different display monitors have different resolutions, so the density of pixels on such monitors will vary. This might cause the sizes of graphics to appear different on different monitors
  • The System.Drawing namespace provides several structures that represent sizes and locations in the coordinate system. The Point structure represents the x-y coordinates of a point on a two-dimensional plane. The Rectangle structure defines the loading width and height of a rectangular shape. The Size structure represents the width and height of a shape
  • Graphics Contexts and Graphics Objects:

    • A C# graphics context represents a drawing surface that enables drawing on the screen. A Graphics object manages a graphics context by controlling how information is drawn. Graphics objects contain methods for drawing, font manipulation, color manipulation and other graphics-related actions. Every derived class of System.Windows.Forms.Form inherits a virtual OnPaint method in which most graphics operations are performed. The arguments to the OnPaint method include a PaintEventArgs object from which we can obtain a Graphics object for the Form. We must obtain the Graphics object on each call to the method, because the properties of the graphics context that the graphics object represents could change. Method OnPaint Triggers the Control’s Paint event
    • When drawing on a Form, you can override method OnPaint to retrieve a Graphics object from argument PaintEventArgs or to create a new Graphics object associated with the appropriate surface
    • To override the inherited OnPaint method, use the following method header:

      • protected override void OnPaint( PaintEventArgs e )
      • Next, extract the incoming Graphics object from argument PaintEventArg, as in
      • Graphics graphicsObject = e.Graphics
      • Variable graphicsObject can now be used to draw shapes and strings on the form
    • Calling the OnPaint method raises the Paint event. Instead of overriding the OnPaint method, programmers can add an event handler for the Paint event. Visual Studio .NET generates the Paint event handler in this form

      • protected void MyEventHandler_Paint(object sender, PaintEventArgs e )
    • You can force a call to OnPaint by calling a Control’s Invalidate method. This method refreshes a control and implicitly repaints all its graphical components. Class Control has several overloaded Invalidate methods that allow programmers to update portions of a control
    • Performance Tip: Calling the Invalidate method to refresh the Control can be inefficient if only a small portion of a Control needs refreshing. Calling Invalidate with a Rectangle parameter refreshes only the area designated by the rectangle. This improves program performance
    • Controls, such as Labels and Buttons, do not have their own graphics contexts, but you can create them. To draw on a control, first create a graphics object by invoking the control’s CreateGraphics method, as in:
    • Graphics graphicsObject = controlName.CreateGraphics();
    • Now you can use the methods provided in class Graphics to draw on the control
  • Color Control:

    • Colors can enhance a program’s appearance and help convey meaning. For example, a red traffic light indicates stop, yellow indicates caution and green indicates go. Structure Color defines methods and constants used to manipulate colors
    • Every color can be created from a combination of alpha, red, green and blue components (called ARGB values). All four ARGB components are bytes that represent integer values in the range 0 to 255. The alpha value determines the opacity of the color. For example, the alpha value 0 represents a transparent color, and the value 255 represents an opaque color. Alpha values between 0 and 255 result in a weighted blending effect of the color’s RGB value with that of any background color, causing a semitransparent effect. The first number in the RGB value defines the amount of red in the color, the second defines the amount of green and the third defines the amount of blue. The larger the value, the greater the amount of that particular color. C# enables programmers to choose from almost 17 million colors. If a particular computer cannot display all these colors, it will display the color closest to the one specified. Table 1.0 summarizes some predefined Color constants (all are public and static), and table 2.0 describes several Color methods and properties. For a complete list of predefined Color constants, methods and properties, see the online documentation for the Color structure (msdn2.microsoft.com/en-us/library/system.drawing.color
    • Table 1.0:

Color

RGB Value

Orange

255, 200, 0

Pink

255, 175, 175

Cyan

0, 255, 255

Magenta

255, 0, 255

Yellow

255, 255, 0

Black

0, 0, 0

White

255, 255, 255

Gray

128, 128, 128

Dark Gray

64, 64, 64

Red

255, 0, 0

Green

0, 255, 0

Blue

0, 0, 255

  • Table 2.0:

Method: FromArgb

A static method that creates a color based on red, green and blue values expressed as ints from 0 to 255. The overloaded version allows specification of alpha, red, green and blue values

Method: FromName

A static method that creates a color from a name, passed as a string

Property: A

A byte between 0 and 255, representing the alpha component

Property: R

A byte between 0 and 255, representing the red component

Property: G

A byte between 0 and 255, representing the green component

Property: B

A byte between 0 and 255, representing the blue component

  • Programmers draw shapes and strings with Brushes and Pens. A Pen, which functions similarly to an ordinary pen, is used to draw lines. Most drawing methods require a Pen object. The overloaded Pen constructors allow programmers to specify the colors and widths of the lines that they wish to draw. The System.Drawing namespace also provides a Pens class containing predefined Pens
  • All classes derived from abstract class Brush define objects that color the interiors of graphical shapes. For example, the SolidBrush constructor takes a Color object the color to draw. In most Fill methods, Brushes fill a space with a color, pattern or image. Table 3.0 summarizes various Brushes and their functions:

Class

Description

HatchBrush

Fills a region with a pattern. The pattern is defined by a member of the HatchStyle enumeration, a foreground color (with which the pattern is drawn) and a background color

LinearGradientBrush

Fills a region with a gradual blend of one color to another. Linear gradients are defined along a line. They can be specified by the two colors, the angle of the gradient and either the width of a rectangle or two points

SolidBrush

Fills a region with one color that is specified by a Color object

TextureBrush

Fills a region by repeating a specified Image across the surface

  • Use function invalidate() when you change the plane painting object ‘e.Graphics’ properties
  • Using the ColorDialog to Select Colors from a Color Palette:

    • The predefined GUI component ColorDialog is a dialog box that allows users to select from a palette of available colors or to create custom colors
    • he method sets the ColorDialog’s FullOpen property to True so the dialog displays all available colors, as shown in the screen capture in. When FullOpen is false, the dialog shows only the color swatches
  • Drawing Lines, Rectangles and Ovals:

Graphics Drawing Methods and Descriptions

DrawLine( Pen p, int x1, int y1, int x2, int y2 )

Draws a line from (x1, y1) to (x2, y2). The Pen determines the line’s color, style and width.

DrawRectangle( Pen p, int x, int y, int width, int height )

Draws a rectangle of the specified width and height. The top-left corner of the rectangle is at point (x, y). The Pen determines the rectangle’s color, style and border width.

FillRectangle( Brush b, int x, int y, int width, int height )

Draws a solid rectangle of the specified width and height. The top-left corner of the rectangle is at point (x, y). The Brush determines the fill pattern inside the rectangle.

DrawEllipse(Pen p, int x, int y, int width, int height )

Draws an ellipse inside a bounding rectangle of the specified width and height. The top-left corner of the bounding rectangle is located at (x, y). The Pen determines the color, style and border width of the ellipse.

FillEllipse( Brush b, int x, int y, int width, int height )

Draws a filled ellipse inside a bounding rectangle of the specified width and height. The topleft corner of the bounding rectangle is located at (x, y). The Brush determines the pattern inside the ellipse

  • See Project Solution: Drawing Lines Rectangles Ellipses
  • Drawing Arcs:

    • Arcs are portions of ellipses and are measured in degrees, beginning at a starting angle and continuing for a specified number of degrees called the arc angle. An arc is said to sweep (traverse) its arc angle, beginning from its starting angle. Arcs that sweep in a clockwise direction are measured in positive degrees, whereas arcs that sweep in a counterclockwise direction are measured in negative degrees

Graphics Methods And Descriptions

Note: Many of these methods are overloaded consult the documentation for a complete listing.

DrawArc( Pen p, int x, int y, int width, int
								
 height, int startAngle, int sweepAngle )

Draws an arc beginning from angle startAngle (in degrees) and sweeping sweepAngle degrees. The ellipse is defined by a bounding rectangle of width, height and upper-left corner (x,y). The Pen determines the color, border width and style of the arc.

DrawPie( Pen p, int x, int y, int width, int
								
 height, int startAngle, int sweepAngle )

Draws a pie section of an ellipse beginning from angle startAngle (in degrees) and sweeping sweepAngle degrees. The ellipse is defined by a bounding rectangle of width, height and upper-left corner (x,y). The Pen determines the color, border width and style of the arc.

FillPie( Brush b, int x, int y, int width, int
								
 height, int startAngle,

									int sweepAngle )

Functions similarly to DrawPie, except draws a solid arc (i.e., a sector). The Brush determines the fill pattern for the solid arc.

  • Drawing Polygons and Polylines:

    • Polygons are multisided shapes. There are several Graphics methods used to draw polygons DrawLines draws a series of connected lines, DrawPolygon draws a closed polygon and FillPolygon draws a solid polygon.

Method

Description

DrawLines

Draws a series of connected lines. The coordinates of each point are specified in an array of Point objects. If the last point is different from the first point, the figure is not closed.

DrawPolygon

Draws a polygon. The coordinates of each point are specified in an array of Point objects. If the last point is different from the first point, those two points are connected to close the polygon.

FillPolygon

Draws a solid polygon. The coordinates of each point are specified in an array of Point objects. If the last point is different from the first point, those two points are connected to close the polygon.

  • Loading, Displaying and Scaling Images:

    • See projects: Imageresizing
  • Windows Media Player:

    • The Windows Media Player control enables an application to play video and sound in many multimedia formats. These include MPEG (Motion Pictures Experts Group) audio and video, AVI (audio-video interleave) video, WAV (Windows wave-file format) audio and MIDI (Musical Instrument Digital Interface) audio. Users can find pre-existing audio and video on the Internet, or they can create their own files, using available sound and graphics packages
    • The application in "Media Player" demonstrates the Windows Media Player control. To use this control, you must add the control to the Toolbox. First select Tools > Choose Toolbox Items… to display the Choose Toolbox Items dialog. Click the COM components tab, then scroll down and select the option Windows Media Player. Click the OK button to dismiss the dialog. The Windows Media Player control now appears at the bottom of the Toolbox
  • Microsoft Agent:

Microsoft Agent is a technology used to add interactive animated characters to Windows applications or Web pages. Microsoft Agent characters can speak and respond to user input via speech recognition and synthesis. Microsoft employs its Agent technology in applications such as Word, Excel and PowerPoint. Agents in these programs aid users in finding answers to questions and in understanding how the applications function

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s