Sie sind auf Seite 1von 8

Graphics and Multimedia

GDI stands for Graphic Device Interface. In Microsoft Windows, GDI is a way to work with paining graphic objects such as painting on windows, forms or other media. GDI+ is an advance version of GDI and is an application programming interface (API) that provides classes for creating twodimensional vector graphics, manipulating fonts and inserting images.

GDI+ namespaces
The following table provides an overview of the main namespaces you'll need to explore to find the GDI+ base classes. You should note that almost all of the classes and structs used are taken from the System.Drawing namespace. Namespace System.Drawing System.Drawing.Drawing2D System.Drawing.Imaging System.Drawing.Printing System.Drawing.Design System.Drawing.Text Description Contains most of the classes, structs, enums, and delegates concerned with the basic functionality of drawing Provides most of the support for advanced 2D and vector drawing, including antialiasing, geometric transformations, and graphics paths Contains various classes that assist in the manipulation of images (bitmaps, GIF files, and so on) Contains classes to assist when specifically targeting a printer or print preview window as the "output device" Contains some predefined dialog boxes, property sheets, and other user interface elements concerned with extending the design-time user interface Contains classes to perform more advanced manipulation of fonts and font families

Drawing Classes and the Coordinate System 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. These methods usually require a Pen or Brush object to render a shape. A Pen draws shape outlines; a 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. GDI+'s coordinate system identifies points on the screen. The upper-left corner of a control has the coordinates (0, 0). The xcoordinate 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.

Programmers position text and shapes on the screen by specifying their coordinates, which are measured in pixels the smallest units of resolution on a display monitor. The Point structure represents the x-y coordinates of a point on a two-dimensional plane. The Rectangle structure defines the location, width and height of a rectangular shape. The Size structure represents the width and height of a shape.

Graphics Contexts and Graphics Objects


A 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. The OnPaint method 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 PaintEventArgs, as in: Graphics graphicsObject = e.Graphics; Variable graphicsObject can now be used to draw shapes and strings on the form. Instead of overriding the OnPaint method, programmers can add an event handler for the Paint event. protected void MyEventHandler_Paint(object sender, PaintEventArgs e ) When any control (such as a TextBox or Label) is displayed, that control's OnPaint method is called. You can force a call to OnPaint by calling a Control's Invalidate method to indicate that the control should be refreshed. This method refreshes a control and implicitly repaints all its graphical components. 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, and then use the Graphics object's methods to draw on the control. 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 are integer values in the range 0-255. The alpha value determines the opacity of the color. 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.

Figure 17.3 Color structure static constants and their RGB values Constants in structure Color Orange Pink Cyan RGB value 255, 200, 0 255, 175, 175 0, 255, 255

Figure 17.3 Color structure static constants and their RGB values Constants in structure Color Magenta Yellow Black White Gray DarkGray Red Green Blue RGB value 255, 0, 255 255, 255, 0 0, 0, 0 255, 255, 255 128, 128, 128 64, 64, 64 255, 0, 0 0, 255, 0 0, 0, 255

Figure 17.4 Color structure members Structure Color methods and properties Common Methods FromArgb Method FromArgb has three and four-parameter versions (all argument values must be int between 0 and 255, inclusive). Both take int arguments specifying the amount of red, green and blue. The four-argument version also allows the user to specify the alpha component; the threeargument version defaults the alpha to 255 (opaque). Both methods return a Color object. A static method that creates a color from a name, passed as a string. Description

FromName Common Properties A R G B

A byte between 0 and 255, representing the alpha component. A byte between 0 and 255, representing the red component. A byte between 0 and 255, representing the green component. A byte between 0 and 255, representing the blue component. // color for back rectangle private Color backColor = Color.Wheat; // color for front rectangle private Color frontColor = Color.FromArgb( 100, 0, 0, 255 ); A 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 provides a Pens class containing predefined Pens. Derived classes of Brush define objects that color the interiors of graphical shapes. Figure 17.5 Classes that derive from class Brush

Class HatchBrush

Description 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.

Figure 17.5 Classes that derive from class Brush Class Description

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. The SolidBrush constructor takes a Color object representing the color to draw.

TextureBrush

Fills a region by repeating a specified Image across the surface.

// create solid brush object SolidBrush brush = new SolidBrush( Color.Black ); Fill methods use Brushes to fill a space with a color, pattern or image. Graphics method FillRectangle draws a filled-in rectangle. FillRectangle takes as parameters a Brush, the x- and ycoordinates of the rectangle's upper-left corner and its width and height. // set brush color and display back rectangle brush.Color = backColor; graphicsObject.FillRectangle( brush, 45, 20, 150, 120 ); There are several overloaded DrawString methods; one takes as arguments the string to display, the display Font, the Brush to use for drawing and the coordinates of the string's first character. // display name of backColor graphicsObject.DrawString( backColor.Name, this.Font, brush, 40, 5 ); Class Color's static method FromName creates a new Color object from a string. // set backColor to color specified in text box backColor = Color.FromName( colorNameTextBox.Text ); ColorDialog is a dialog box that allows users to select from a palette of available colors or to create custom colors. An application retrieves the user's selection via the ColorDialog's Color property. Setting ColorDialog's FullOpen property to true indicates that the dialog should display all available colors. When FullOpen is false, the dialog shows only color swatches.

Font Control
Figure 17.8 Font class read-only properties Property Bold FontFamily Height Italic Name Size Description Returns true if the font is bold. Returns the Font's FontFamily a grouping structure to organize fonts and define their similar properties. Returns the height of the font. Returns True if the font is italic. Returns the font's name as a string. Returns a float value indicating the current font size measured in design units (design units are any specified unit of measurement for the font).

SizeInPoints Returns a float value indicating the current font size measured in points. Strikeout Underline Returns true if the font is in strikeout format. Returns true if the font is underlined.

Some Font constructors accept a GraphicsUnit enumeration argument that allows you to specify the unit of measurement for the font size. Members of the GraphicsUnit enumeration include Point (1/72 inch), Display (1/75 inch), Document (1/300 inch), Millimeter, Inch and Pixel. Most Font constructors require a font name, the font size and the font style. The font style is specified with a constant from the FontStyle enumeration (Bold, Italic, Regular, Strikeout and Underline, or a combination of these). You can combine font styles with the | operator. // arial, 12 pt bold FontStyle style = FontStyle.Bold; Font arial = new Font( "Arial" , 12, style ); You can determine a font's metrics (or properties), such as height, descent (the amount that characters dip below the baseline), ascent (the amount that characters rise above the baseline) and leading (the difference between the ascent of one line and the decent of the previous line).

Class FontFamily defines characteristics common to a group of related fonts. Class FontFamily provides methods to determine the font metrics shared by members of a particular family. Figure 17.11. FontFamily methods that return font-metric information.

Method GetCellAscent GetCellDescent GetEmHeight

Description Returns an int representing the ascent of a font as measured in design units. Returns an int representing the descent of a font as measured in design units. Returns an int representing the height of a font as measured in design units.

GetLineSpacing Returns an int representing the distance between two consecutive lines of text as measured in design units.

Drawing Lines, Rectangles and Ovals


Figure 17.13 Graphics methods that draw 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)

Figure 17.13 Graphics methods that draw lines, rectangles and ovals Graphics Drawing Methods and Descriptions 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 top-left corner of the bounding rectangle is located at (x, y). The Brush determines the pattern inside the ellipse. Methods that draw hollow shapes typically require as arguments a Pen and four ints. Methods that draw solid shapes typically require as arguments a Brush and four ints.

// override Form OnPaint method 17 protected override void OnPaint( PaintEventArgs paintEvent ) 18 { 19 // get graphics object 20 Graphics g = paintEvent.Graphics; 21 SolidBrush brush = new SolidBrush( Color.Blue ); 22 Pen pen = new Pen( Color.AliceBlue ); 23 24 // create filled rectangle 25 g.FillRectangle( brush, 90, 30, 150, 90 ); 26 27 // draw lines to connect rectangles 28 g.DrawLine( pen, 90, 30, 110, 40 ); 29 g.DrawLine( pen, 90, 120, 110, 130 ); 30 g.DrawLine( pen, 240, 30, 260, 40 ); 31 g.DrawLine( pen, 240, 120, 260, 130 ); 32 33 // draw top rectangle 34 g.DrawRectangle( pen, 110, 40, 150, 90 ); 35 36 // set brush to red 37 brush.Color = Color.Red; 39 40 41 42 43 44 45 46 47 48 // draw base Ellipse g.FillEllipse( brush, 280, 75, 100, 50 ); // draw connecting lines g.DrawLine( pen, 380, 55, 380, 100 ); g.DrawLine( pen, 280, 55, 280, 100 ); // draw Ellipse outline g.DrawEllipse( pen, 280, 30, 100, 50 ); } // end method OnPaint

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. Arcs that sweep in a clockwise direction are measured in positive degrees. Arcs that sweep in a counterclockwise direction are measured in negative degrees.

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. //Forms Paint Method to draw arcs private void DrawArcs_Paint( object sender, PaintEventArgs e ) 18 { 19 // get graphics object 20 Graphics graphicsObject = e.Graphics; 21 Rectangle rectangle1 = new Rectangle( 15, 35, 80, 80 ); 22 SolidBrush brush1 = new SolidBrush( Color.Firebrick ); 23 Pen pen1 = new Pen( brush1, 1 ); 24 SolidBrush brush2 = new SolidBrush( Color.DarkBlue ); 25 Pen pen2 = new Pen( brush2, 1 ); 26 27 // start at 0 and sweep 360 degrees 28 graphicsObject.DrawRectangle( pen1, rectangle1 ); 29 graphicsObject.DrawArc( pen2, rectangle1, 0, 360 ); 30 31 // start at 0 and sweep 110 degrees 32 rectangle1.Location = new Point( 100, 35 ); 33 graphicsObject.DrawRectangle( pen1, rectangle1 ); 34 graphicsObject.DrawArc( pen2, rectangle1, 0, 110 ); 35 36 // start at 0 and sweep -270 degrees 37 rectangle1.Location = new Point( 185, 35 ); 38 graphicsObject.DrawRectangle( pen1, rectangle1 ); 39 graphicsObject.DrawArc( pen2, rectangle1, 0, -270 ); 40 41 // start at 0 and sweep 360 degrees 42 rectangle1.Location = new Point( 15, 120 ); 43 rectangle1.Size = new Size( 80, 40 ); 44 graphicsObject.DrawRectangle( pen1, rectangle1 ); 45 graphicsObject.FillPie( brush2, rectangle1, 0, 360 ); 46 47 // start at 270 and sweep -90 degrees 48 rectangle1.Location = new Point( 100, 120 ); 49 graphicsObject.DrawRectangle( pen1, rectangle1 ); 50 graphicsObject.FillPie( brush2, rectangle1, 270, -90 ); 51 52 // start at 0 and sweep -270 degrees 53 rectangle1.Location = new Point( 185, 120 ); 54 graphicsObject.DrawRectangle( pen1, rectangle1 ); 55 graphicsObject.FillPie( brush2, rectangle1, 0, -270 ); 56 } // end method DrawArcs_Paint

The Point constructor takes as arguments the x- and y-coordinates of the new point. The Location property determines the upper-left corner of the Rectangle. The Size property of a Rectangle determines the arc's height and width.

Drawing Polygons and Polylines Polygons are multisided shapes. There are several Graphics methods used to draw polygons. DrawLines draws a series of connected points, DrawPolygon draws a closed polygon and FillPolygon draws a solid polygon. Figure 17.19 Graphics methods for drawing polygons Method DrawLines Description 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.

Das könnte Ihnen auch gefallen