2006 pearson education, inc. all rights reserved. 1 17 graphics and multimedia

108
1 2006 Pearson Education, Inc. All rights rese 1 7 Graphics and Multimedia

Post on 21-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

1

2006 Pearson Education, Inc. All rights reserved.

1717

Graphics and Multimedia

Page 2: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

2

2006 Pearson Education, Inc. All rights reserved.

One picture is worth ten thousand words. — Chinese proverb

Treat nature in terms of the cylinder, the sphere, the cone, all in perspective.

— Paul Cezanne

Nothing ever becomes real till it is experienced—even a proverb is no proverb to you till your life has illustrated it.

— John Keats

A picture shows me at a glance what it takes dozens of pages of a book to expound.

— Ivan Sergeyevich

Page 3: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

3

2006 Pearson Education, Inc. All rights reserved.

OBJECTIVES

In this chapter 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.

Page 4: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

4

2006 Pearson Education, Inc. All rights reserved.

17.1   Introduction

17.2   Drawing Classes and the Coordinate System

17.3   Graphics Contexts and Graphics Objects

17.4   Color Control

17.5   Font Control

17.6   Drawing Lines, Rectangles and Ovals

17.7   Drawing Arcs

17.8   Drawing Polygons and Polylines

17.9   Advanced Graphics Capabilities

17.10   Introduction to Multimedia

17.11   Loading, Displaying and Scaling Images

17.12   Animating a Series of Images

17.13   Windows Media Player

17.14   Microsoft Agent

17.15   Wrap-Up

Page 5: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

5

2006 Pearson Education, Inc. All rights reserved.

17.1 Introduction

• Overview of C#’s tools for drawing 2-D shapes and for controlling colors and fonts

– Namespace System.Drawing • Many sophisticated drawing capabilities that make up the .NET resource

GDI+– GDI+ is an application programming interface (API)

• For creating 2-D vector graphics, manipulating fonts and inserting images

– Class Image • Store and manipulate images of various formats

• Multimedia examples– Build an animation– Use the Windows Media Player control – Use Microsoft Agent

• For adding interactive animated characters to applications or Web pages

Page 6: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

6

2006 Pearson Education, Inc. All rights reserved.

17.2 Drawing Classes and the Coordinate System

•System.Drawing– Class Graphics

• Methods used for drawing strings, lines, rectangles and etc.

– Class Pen and/or Brush• Render a specified shape

– Color structure• Set colors of various graphical components

• Allow to create new colors

– Class Font• Contains properties that define unique fonts

– Class FontFamily• Contains methods for obtaining font information

Page 7: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

7

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.1 | System.Drawing namespace’s classes and structures.

Page 8: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

8

2006 Pearson Education, Inc. All rights reserved.

17.2 Drawing Classes and the Coordinate System (Cont.)

• GDI’s coordinate system– By default, the upper-left corner of a GUI component has the

coordinates (0, 0)– A coordinate pair

• x-coordinate – The horizontal distance from the upper-left corner

• y-coordinate – The vertical distance from the upper-left corner

– Coordinate units are measured in pixels• The smallest units of resolution on a display monitor

– Point structure• Represents the x-y coordinates of a point on a two 2-D plane

– Size structure• Represents width and height of a shape

Page 9: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

9

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 17.1

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.

Page 10: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

10

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.2 | GDI+ coordinate system. Units are measured in pixels.

Page 11: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

11

2006 Pearson Education, Inc. All rights reserved.

17.3 Graphics Contexts and Graphical Objects

• Graphics– Graphical context represents drawing surface

– Graphics objects contain methods for graphics-related actions

– Derived classes of System.Windows.Forms.Form inherits virtual OnPaint method • OnPaint method’s argument includes a PaintEventArgs object

to obtain a Graphics object for the Form

– Programmers seldom call the OnPaint method directly

• Drawing graphics is an event-driven process

– Control’s Invalidate method forces a call to OnPaint

– By default, controls do not have their own graphics contexts

Page 12: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

12

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 17.1

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.

Page 13: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

13

2006 Pearson Education, Inc. All rights reserved.

17.4 Color Control• Colors

– Are 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• Method FromArgb

– Allows you to set these values

• Some methods/classes related to color control– Derived classes from abstract class Brush

• Define the color of interiors of graphical shapes– Graphics has several overloaded DrawString methods– Color’s static method FromName

• Create new Color defined by user– ColorDialog GUI component

• A dialog box that allows users to select from a palette of available colors or to create custom colors

Page 14: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

14

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.3 | Color structure static constants and their RGB values.

Constants in structure Color RGB value

Constants in structure Color RGB value

Orange 255, 200, 0 White 255, 255, 255

Pink 255, 175, 175 Gray 128, 128, 128

Cyan 0, 255, 255 DarkGray 64, 64, 64

Magenta 255, 0, 255 Red 255, 0, 0

Yellow 255, 255, 0 Green 0, 255, 0

Black 0, 0, 0 Blue 0, 0, 255

Page 15: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

15

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.4 | Color structure members.

Structure Color methods and properties Description

Common Methods

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.

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

Common Properties

A A byte between 0 and 255, representing the alpha component.

R A byte between 0 and 255, representing the red component.

G A byte between 0 and 255, representing the green component.

B A byte between 0 and 255, representing the blue component.

Page 16: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

16

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.5 | Classes that derive from class Brush.

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.

Page 17: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

17

2006 Pearson Education, Inc. All rights reserved.

1 // Fig 17.6: ShowColors.cs

2 // Color value and alpha demonstration.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 public partial class ShowColors : Form

8 {

9 // color for back rectangle

10 private Color backColor = Color.Wheat;

11

12 // color for front rectangle

13 private Color frontColor = Color.FromArgb( 100, 0, 0, 255 );

14

15 // default constructor

16 public ShowColors()

17 {

18 InitializeComponent();

19 } // end constructor

20

21 // override Form OnPaint method

22 protected override void OnPaint( PaintEventArgs e )

23 {

24 Graphics graphicsObject = e.Graphics; // get graphics

25

26 // create text brush

27 SolidBrush textBrush = new SolidBrush( Color.Black );

Outline

ShowColors.cs

(1 of 4)

private instance variable to store the back rectangle's color

private instance variable to store the front rectangle's color

Override OnPaint to customize the graphics operations that are performed

Retrieve the Graphics object

Create SolidBrush object to for drawing solid shape

Page 18: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

18

2006 Pearson Education, Inc. All rights reserved.

28

29 // create solid brush

30 SolidBrush brush = new SolidBrush( Color.White );

31

32 // draw white background

33 graphicsObject.FillRectangle( brush, 4, 4, 275, 180 );

34

35 // display name of backColor

36 graphicsObject.DrawString( backColor.Name, this.Font,

37 textBrush, 40, 5 );

38

39 // set brush color and display back rectangle

40 brush.Color = backColor;

41 graphicsObject.FillRectangle( brush, 45, 20, 150, 120 );

42

43 // display Argb values of front color

44 graphicsObject.DrawString( "Alpha: " + frontColor.A +

45 " Red: " + frontColor.R + " Green: " + frontColor.G +

46 " Blue: " + frontColor.B, this.Font, textBrush, 55, 165 );

47

48 // set brush color and display front rectangle

49 brush.Color = frontColor;

50 graphicsObject.FillRectangle( brush, 65, 35, 170, 130 );

51 } // end method OnPaint

52

Outline

ShowColors.cs

(2 of 4)

Create SolidBrush object for drawing solid shape

Give the retrieved Graphics object a white background using brush

Output the background color by drawing to the Graphics object

Draw the back rectangle to Graphics object

Draw the front rectangle to Graphics object

Output the Argb value of front rectangle by drawing to the Graphics object

Page 19: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

19

2006 Pearson Education, Inc. All rights reserved.

53 // handle colorNameButton click event

54 private void colorNameButton_Click( object sender, EventArgs e )

55 {

56 // set backColor to color specified in text box

57 backColor = Color.FromName( colorNameTextBox.Text );

58

59 Invalidate(); // refresh Form

60 } // end method colorNameButton_Click

61

62 // handle colorValueButton click event

63 private void colorValueButton_Click( object sender, EventArgs e )

64 {

65 // obtain new front color from text boxes

66 frontColor = Color.FromArgb(

67 Convert.ToInt32( alphaTextBox.Text ),

68 Convert.ToInt32( redTextBox.Text ),

69 Convert.ToInt32( greenTextBox.Text ),

70 Convert.ToInt32( blueTextBox.Text ) );

71

72 Invalidate(); // refresh Form

73 } // end method colorValueButton_Click

74 } // end class ShowColors

Outline

ShowColors.cs

(3 of 4)

Allow user to change background color

Call OnPaint to redraw

Allow user to change the front rectangle’s color

Call OnPaint to redraw

Page 20: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

20

2006 Pearson Education, Inc. All rights reserved.

Outline

ShowColors.cs

(4 of 4)

Page 21: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

21

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.7: ShowColorsComplex.cs

2 // ColorDialog used to change background and text color.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // allows users to change colors using a ColorDialog

8 public partial class ShowColorsComplex : Form

9 {

10 // create ColorDialog object

11 private static ColorDialog colorChooser = new ColorDialog();

12

13 // default constructor

14 public ShowColorsComplex()

15 {

16 InitializeComponent();

17 } // end constructor

18

19 // change text color

20 private void textColorButton_Click( object sender, EventArgs e )

21 {

22 // get chosen color

23 DialogResult result = colorChooser.ShowDialog();

24

25 if ( result == DialogResult.Cancel )

26 return;

Outline

ShowColorsComplex.cs

(1 of 3)

Create a ColorDialog object

Allow user to choose from a variety of colors

Check to see if the user pressed “Cancel”

Page 22: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

22

2006 Pearson Education, Inc. All rights reserved.

27

28 // assign forecolor to result of dialog

29 backgroundColorButton.ForeColor = colorChooser.Color;

30 textColorButton.ForeColor = colorChooser.Color;

31 } // end method textColorButton_Click

32

33 // change background color

34 private void backgroundColorButton_Click( object sender, EventArgs e )

35 {

36 // show ColorDialog and get result

37 colorChooser.FullOpen = true;

38 DialogResult result = colorChooser.ShowDialog();

39

40 if ( result == DialogResult.Cancel )

41 return;

42

43 // set background color

44 this.BackColor = colorChooser.Color;

45 } // end method backgroundColorButton_Click

46 } // end class ShowColorsComplex

Outline

ShowColorsComplex.cs

(2 of 3)

Change color to user’s selection

Change color to user’s selection

Allow user to choose from a variety of colors

Page 23: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

23

2006 Pearson Education, Inc. All rights reserved.

Outline

ShowColorsComplex.cs

(3 of 3)

Page 24: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

24

2006 Pearson Education, Inc. All rights reserved.

17.5 Font Control

• Font– Properties of Font objects cannot be modified

• If you need a different Font, must create a new Font object

– Size property • Returns the font size as measured in design units

– SizeInPoints property• Returns the font size as measured in points

– GraphicsUnit enumeration • Unit of measurement that describes the font size

• FontFamily– Defines characteristics common to a group of related fonts– Provides several methods to determine the font metrics that are shared

by members of a particular family

Page 25: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

25

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.8 | Font class read-only properties.

Property Description

Bold Returns true if the font is bold.

FontFamily Returns the Font’s FontFamily—a grouping structure to organize fonts and define their similar properties.

Height Returns the height of the font.

Italic Returns true if the font is italic.

Name Returns the font’s name as a string.

Size 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 Returns true if the font is in strikeout format.

Underline Returns true if the font is underlined.

Page 26: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

26

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 17.1

Specifying a font that is not available on a system is a logic error. If this occurs, C# will substitute that system’s default font.

Page 27: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

27

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.9 UsingFonts.cs

2 // Fonts and FontStyles.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // demonstrate font constructors and properties

8 public partial class UsingFonts : Form

9 {

10 // default constructor

11 public UsingFonts()

12 {

13 InitializeComponent();

14 } // end constructor

15

16 // demonstrate various font and style settings

17 protected override void OnPaint( PaintEventArgs paintEvent )

18 {

19 Graphics graphicsObject = paintEvent.Graphics;

20 SolidBrush brush = new SolidBrush( Color.DarkBlue );

21

22 // arial, 12 pt bold

23 FontStyle style = FontStyle.Bold;

24 Font arial = new Font( "Arial" , 12, style );

25

26 // times new roman, 12 pt regular

27 style = FontStyle.Regular;

28 Font timesNewRoman = new Font( "Times New Roman", 12, style );

29

Outline

UsingFonts.cs

(1 of 3)

Change font style to bold Arial

Change font style to Times New Roman

Page 28: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

28

2006 Pearson Education, Inc. All rights reserved.

30 // courier new, 16 pt bold and italic

31 style = FontStyle.Bold | FontStyle.Italic;

32 Font courierNew = new Font( "Courier New", 16, style );

33

34 // tahoma, 18 pt strikeout

35 style = FontStyle.Strikeout;

36 Font tahoma = new Font( "Tahoma", 18, style );

37

38 graphicsObject.DrawString( arial.Name +

39 " 12 point bold.", arial, brush, 10, 10 );

40

41 graphicsObject.DrawString( timesNewRoman.Name +

42 " 12 point plain.", timesNewRoman, brush, 10, 30 );

43

44 graphicsObject.DrawString( courierNew.Name +

45 " 16 point bold and italic.", courierNew,

46 brush, 10, 54 );

Outline

UsingFonts.cs

(2 of 3)

Change font style to italic Courier New

Change font style to strikeout Tahoma

Output font styles to screen by drawing to graphicsObject

Page 29: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

29

2006 Pearson Education, Inc. All rights reserved.

47

48 graphicsObject.DrawString( tahoma.Name +

49 " 18 point strikeout.", tahoma, brush, 10, 75 );

50 } // end method OnPaint

51 } // end class UsingFonts

Outline

UsingFonts.cs

(3 of 3)

Output font styles to screen by drawing to graphicsObject

Page 30: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

30

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.10 | Font metrics illustration.

Page 31: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

31

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.11 | FontFamily methods that return font-metric information.

Method Description

GetCellAscent Returns an int representing the ascent of a font as measured in design units.

GetCellDescent Returns an int representing the descent of a font as measured in design units.

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

Page 32: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

32

2006 Pearson Education, Inc. All rights reserved.

1 // Fig 17.12: UsingFontMetrics.cs

2 // Displaying font metric information

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // display font information

8 public partial class UsingFontMetrics : Form

9 {

10 // default constructor

11 public UsingFontMetrics()

12 {

13 InitializeComponent();

14 } // end constructor

15

16 // displays font information

17 protected override void OnPaint( PaintEventArgs paintEvent )

18 {

19 Graphics graphicsObject = paintEvent.Graphics;

20 SolidBrush brush = new SolidBrush( Color.DarkBlue );

21

22 // Arial font metrics

23 Font arial = new Font( "Arial", 12 );

24 FontFamily family = arial.FontFamily;

25

26 // display Arial font metrics

27 graphicsObject.DrawString( "Current Font: " +

28 arial, arial, brush, 10, 10 );

29

Outline

UsingFontMetrics.cs

(1 of 3)

Create a FontFamily object to determine the front metrics of Arial

Page 33: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

33

2006 Pearson Education, Inc. All rights reserved.

30 graphicsObject.DrawString( "Ascent: " +

31 family.GetCellAscent( FontStyle.Regular ), arial,

32 brush, 10, 30 );

33

34 graphicsObject.DrawString( "Descent: " +

35 family.GetCellDescent( FontStyle.Regular ), arial,

36 brush, 10, 50 );

37

38 graphicsObject.DrawString( "Height: " +

39 family.GetEmHeight( FontStyle.Regular ), arial,

40 brush, 10, 70 );

41

42 graphicsObject.DrawString( "Leading: " +

43 family.GetLineSpacing( FontStyle.Regular ), arial,

44 brush, 10, 90 );

45

46 // display Sans Serif font metrics

47 Font sanSerif = new Font( "Microsoft Sans Serif",

48 14, FontStyle.Italic );

49 family = sanSerif.FontFamily;

50

51 graphicsObject.DrawString( "Current Font: " +

52 sanSerif, sanSerif, brush, 10, 130 );

53

54 graphicsObject.DrawString( "Ascent: " +

55 family.GetCellAscent( FontStyle.Regular ), sanSerif,

56 brush, 10, 150 );

Outline

UsingFontMetrics.cs

(2 of 3)

Output font style’s ascent

Output font style’s descent

Output font style’s height

Output font style’s spacing

Change the FontFamily object to determine the front metrics of Sans Serif

Output font style’s ascent

Page 34: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

34

2006 Pearson Education, Inc. All rights reserved.

57

58 graphicsObject.DrawString( "Descent: " +

59 family.GetCellDescent( FontStyle.Regular ), sanSerif,

60 brush, 10, 170 );

61

62 graphicsObject.DrawString( "Height: " +

63 family.GetEmHeight( FontStyle.Regular ), sanSerif,

64 brush, 10, 190 );

65

66 graphicsObject.DrawString( "Leading: " +

67 family.GetLineSpacing( FontStyle.Regular ), sanSerif,

68 brush, 10, 210 );

69 } // end method OnPaint

70 } // end class UsingFontMetrics

Outline

UsingFontMetrics.cs

(3 of 3)

Output font style’s descent

Output font style’s height

Output font style’s spacing

Page 35: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

35

2006 Pearson Education, Inc. All rights reserved.

17.6 Drawing Lines, Rectangles and Ovals

• Each of the drawing methods has several overloaded versions– 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

– The first two int arguments represent the coordinates of the upper-left corner of the shape

– The last two ints indicate the shape’s width and height

– Methods FillRectangle and DrawRectangle • Draw rectangles on the screen

– Methods FillEllipse and DrawEllipse • Draw ellipses on the screen

Page 36: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

36

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.13 | Graphics methods that draw lines, rectangles and ovals. (Part 1 of 2.)

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.

Page 37: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

37

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.13 | Graphics methods that draw lines, rectangles and ovals. (Part 2 of 2.)

Graphics Drawing Methods and Descriptions

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 top-left corner of the bounding rectangle is located at (x, y). The Brush determines the pattern inside the ellipse.

Page 38: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

38

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.14: LinesRectanglesOvals.cs

2 // Demonstrating lines, rectangles and ovals.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // draw shapes on Form

8 public partial class LinesRectanglesOvals : Form

9 {

10 // default constructor

11 public LinesRectanglesOvals()

12 {

13 InitializeComponent();

14 } // end constructor

15

16 // 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 );

Outline

LinesRectanglesOvals.cs

(1 of 3)

Draw the back rectangle filled in with blue

Page 39: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

39

2006 Pearson Education, Inc. All rights reserved.

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;

38

39 // draw base Ellipse

40 g.FillEllipse( brush, 280, 75, 100, 50 );

41

42 // draw connecting lines

43 g.DrawLine( pen, 380, 55, 380, 100 );

44 g.DrawLine( pen, 280, 55, 280, 100 );

Outline

LinesRectanglesOvals.cs

(2 of 3)

Draw lines to connect the rectangle to make a box

Draw the front rectangle

Draw the bottom ellipse filled in with red

Draw lines to connect the ellipses to make a cylinder

Page 40: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

40

2006 Pearson Education, Inc. All rights reserved.

45

46 // draw Ellipse outline

47 g.DrawEllipse( pen, 280, 30, 100, 50 );

48 } // end method OnPaint

49 } // end class LinesRectanglesOvals

Outline

LinesRectanglesOvals.cs

(3 of 3)

Draw the top ellipse

Page 41: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

41

2006 Pearson Education, Inc. All rights reserved.

17.7 Drawing Arcs

• Arcs – Portions of ellipses and are measured in degrees

• Begin at a starting angle • Continue for a specified number of degrees (the arc angle)

– An arc is said to sweep its arc angle• Begin from its starting angle• Clockwise direction is measured in + degree• Counterclockwise direction is measured in - degree

– The Graphics methods used to draw arcs:• DrawArc• DrawPie • FillPie

Page 42: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

42

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.15 | Ellipse bounded by a rectangle.

Page 43: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

43

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.16 | Positive and negative arc angles.

Page 44: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

44

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.17 | Graphics methods for drawing arcs.

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.

Page 45: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

45

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.18: DrawingArcs.cs

2 // Drawing various arcs on a Form.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // draws various arcs

8 public partial class DrawArcs : Form

9 {

10 // default constructor

11 public DrawArcs()

12 {

13 InitializeComponent();

14 } // end constructor

15

16 // draw arcs

17 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

Outline

DrawingArcs.cs

(1 of 3)

Draws a circle

Page 46: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

46

2006 Pearson Education, Inc. All rights reserved.

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

57 } // end class DrawArcs

Outline

DrawingArcs.cs

(2 of 3)

Draws an arc from 0 to 110

degrees

Draws an arc from 0 to -270

degrees

Draws filled circle

Draws a filled arc from 270 to -90

degrees

Draws a filled arc from 0 to -270

degrees

Page 47: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

47

2006 Pearson Education, Inc. All rights reserved.

Outline

DrawingArcs.cs

(3 of 3)

Page 48: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

48

2006 Pearson Education, Inc. All rights reserved.

17.8 Drawing Polygons and Polylines

• Polygons – Multisided shapes

– Several Graphics methods used to draw polygons:

– DrawLines • Draws a series of connected lines

– DrawPolygon • Draws a closed polygon

– FillPolygon • Draws a solid polygon

Page 49: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

49

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.19 | Graphics methods for drawing polygons.

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.

Page 50: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

50

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.20: DrawPolygons.cs

2 // Demonstrating polygons.

3 using System;

4 using System.Collections;

5 using System.Drawing;

6 using System.Windows.Forms;

7

8 // demonstrating polygons

9 public partial class PolygonForm : Form

10 {

11 // default constructor

12 public PolygonForm()

13 {

14 InitializeComponent();

15 } // end constructor

16

17 // contains list of polygon vertices

18 private ArrayList points = new ArrayList();

19

20 // initialize default pen and brush

21 Pen pen = new Pen( Color.DarkBlue );

22 SolidBrush brush = new SolidBrush( Color.DarkBlue );

23

24 // draw panel mouse down event handler

25 private void drawPanel_MouseDown( object sender, MouseEventArgs e )

26 {

27 // add mouse position to vertex list

28 points.Add( new Point( e.X, e.Y ) );

29 drawPanel.Invalidate(); // refresh panel

30 } // end method drawPanel_MouseDown

Outline

DrawPolygons.cs

(1 of 5)

Declare a dynamic array to store the vertices of the polygon

Store the polygon’s vertices determined by the

mouse position

Page 51: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

51

2006 Pearson Education, Inc. All rights reserved.

31

32 // draw panel Paint event handler

33 private void drawPanel_Paint( object sender, PaintEventArgs e )

34 {

35 // get graphics object for panel

36 Graphics graphicsObject = e.Graphics;

37

38 // if arraylist has 2 or more points, display shape

39 if ( points.Count > 1 )

40 {

41 // get array for use in drawing functions

42 Point[] pointArray =

43 ( Point[] ) points.ToArray( points[ 0 ].GetType() );

44

45 if ( lineOption.Checked )

46 graphicsObject.DrawLines( pen, pointArray );

47 else if ( polygonOption.Checked )

48 graphicsObject.DrawPolygon( pen, pointArray );

49 else if ( filledPolygonOption.Checked )

50 graphicsObject.FillPolygon( brush, pointArray );

51 } // end if

52 } // end method drawPanel_Paint

53

54 // handle clearButton click event

55 private void clearButton_Click( object sender, EventArgs e )

56 {

57 points.Clear(); // remove points

58 drawPanel.Invalidate(); // refresh panel

59 } // end method clearButton_Click

Outline

DrawPolygons.cs

(2 of 5)Make sure there is more than one point

Extract an array from an ArrayList

Determine which option(s) are checked and draw its

corresponding shape

Clear the points store in the ArrayList

Page 52: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

52

2006 Pearson Education, Inc. All rights reserved.

60

61 // handle polygon RadioButton CheckedChanged event

62 private void polygonOption_CheckedChanged(

63 object sender, System.EventArgs e )

64 {

65 drawPanel.Invalidate(); // refresh panel

66 } // end method polygonOption_CheckedChanged

67

68 // handle line ReadioButton CheckedChanged event

69 private void lineOption_CheckedChanged(

70 object sender, System.EventArgs e )

71 {

72 drawPanel.Invalidate(); // refresh panel

73 } // end method lineOption_CheckedChanged

74

75 // handle filled polygon RadioButton CheckedChanged event

76 private void filledPolygonOption_CheckedChanged(

77 object sender, System.EventArgs e )

78 {

79 drawPanel.Invalidate(); // refresh panel

80 } // end method filledPolygonOption_CheckedChanged

81

82 // handle colorButton Click event

83 private void colorButton_Click( object sender, EventArgs e )

84 {

85 // create new color dialog

86 ColorDialog dialogColor = new ColorDialog();

87

Outline

DrawPolygons.cs

(3 of 5)

Refresh and redraw

Page 53: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

53

2006 Pearson Education, Inc. All rights reserved.

88 // show dialog and obtain result

89 DialogResult result = dialogColor.ShowDialog();

90

91 // return if user cancels

92 if ( result == DialogResult.Cancel )

93 return;

94

95 pen.Color = dialogColor.Color; // set pen to color

96 brush.Color = dialogColor.Color; // set brush

97 drawPanel.Invalidate(); // refresh panel;

98 } // end method colorButton_Click

99 } // end class PolygonForm

Outline

DrawPolygons.cs

(4 of 5)

Check to see if user pressed “Cancel”

Change to the appropriate color

Page 54: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

54

2006 Pearson Education, Inc. All rights reserved.

Outline

DrawPolygons.cs

(5 of 5)

Page 55: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

55

2006 Pearson Education, Inc. All rights reserved.

17.9 Advanced Graphics Capabilities• Class LinearGradientBrush

– Enables users to draw with a color gradient– LinearGradientMode enumeration

• Specifies the gradient’s direction• Class Bitmap

– Produce images in color and gray scale– Graphic’s static method FromImage

• Retrieves the Graphics object associated with an Image• Class GraphicsPath

– Enables the creation of complex shapes from vector-based primitive graphics objects

– Method CloseFigure• Attaches the final vector-graphic object end point to the initial starting point

for the current figure by a straight line• Then starts a new figure

– Method StartFigure • Begins a new figure within the path without closing the previous figure

– Method AddLine • Append a line to the shape

Page 56: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

56

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.21: DrawShapes.cs

2 // Drawing various shapes on a Form.

3 using System;

4 using System.Drawing;

5 using System.Drawing.Drawing2D;

6 using System.Windows.Forms;

7

8 // draws shapes with different brushes

9 public partial class DrawShapesForm : Form

10 {

11 // default constructor

12 public DrawShapesForm()

13 {

14 InitializeComponent();

15 } // end constructor

16

17 // draw various shapes on Form

18 private void DrawShapesForm_Paint( object sender, PaintEventArgs e )

19 {

20 // references to object we will use

21 Graphics graphicsObject = e.Graphics;

22

23 // ellipse rectangle and gradient brush

24 Rectangle drawArea1 = new Rectangle( 5, 35, 30, 100 );

25 LinearGradientBrush linearBrush =

26 new LinearGradientBrush( drawArea1, Color.Blue,

27 Color.Yellow, LinearGradientMode.ForwardDiagonal );

Outline

DrawShapes.cs

(1 of 4)

Create a Rectangle object

Enable user to draw with a color gradient

Page 57: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

57

2006 Pearson Education, Inc. All rights reserved.

28

29 // draw ellipse filled with a blue-yellow gradient

30 graphicsObject.FillEllipse( linearBrush, 5, 30, 65, 100 );

31

32 // pen and location for red outline rectangle

33 Pen thickRedPen = new Pen( Color.Red, 10 );

34 Rectangle drawArea2 = new Rectangle( 80, 30, 65, 100 );

35

36 // draw thick rectangle outline in red

37 graphicsObject.DrawRectangle( thickRedPen, drawArea2 );

38

39 // bitmap texture

40 Bitmap textureBitmap = new Bitmap( 10, 10 );

41

42 // get bitmap graphics

43 Graphics graphicsObject2 =

44 Graphics.FromImage( textureBitmap );

45

46 // brush and pen used throughout program

47 SolidBrush solidColorBrush =

48 new SolidBrush( Color.Red );

49 Pen coloredPen = new Pen( solidColorBrush );

50

51 // fill textureBitmap with yellow

52 solidColorBrush.Color = Color.Yellow;

53 graphicsObject2.FillRectangle( solidColorBrush, 0, 0, 10, 10 );

54

55 // draw small black rectangle in textureBitmap

56 coloredPen.Color = Color.Black;

57 graphicsObject2.DrawRectangle( coloredPen, 1, 1, 6, 6 );

58

Outline

DrawShapes.cs

(2 of 4)

Draw a filled gradient ellipse

Draw a red outlined rectangle

Create a new Bitmap image

Fill Bitmap

Retrieves Graphics object associate with an Image

Page 58: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

58

2006 Pearson Education, Inc. All rights reserved.

59 // draw small blue rectangle in textureBitmap

60 solidColorBrush.Color = Color.Blue;

61 graphicsObject2.FillRectangle( solidColorBrush, 1, 1, 3, 3 );

62

63 // draw small red square in textureBitmap

64 solidColorBrush.Color = Color.Red;

65 graphicsObject2.FillRectangle( solidColorBrush, 4, 4, 3, 3 );

66

67 // create textured brush and

68 // display textured rectangle

69 TextureBrush texturedBrush =

70 new TextureBrush( textureBitmap );

71 graphicsObject.FillRectangle( texturedBrush, 155, 30, 75, 100 );

72

73 // draw pie-shaped arc in white

74 coloredPen.Color = Color.White;

75 coloredPen.Width = 6;

76 graphicsObject.DrawPie( coloredPen, 240, 30, 75, 100, 0, 270 );

77

78 // draw lines in green and yellow

79 coloredPen.Color = Color.Green;

80 coloredPen.Width = 5;

81 graphicsObject.DrawLine( coloredPen, 395, 30, 320, 150 );

82

83 // draw a rounded, dashed yellow line

84 coloredPen.Color = Color.Yellow;

85 coloredPen.DashCap = DashCap.Round;

86 coloredPen.DashStyle = DashStyle.Dash;

87 graphicsObject.DrawLine( coloredPen, 320, 30, 395, 150 );

88 } // end method DrawShapesForm_Paint

89 } // end class DrawShapesForm

Outline

DrawShapes.cs

(3 of 4)

Fill Bitmap

Draw rectangle with Bitmap image

Draw white pie arc

Draw a green line

Draw a yellow dashed line

Page 59: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

59

2006 Pearson Education, Inc. All rights reserved.

Outline

DrawShapes.cs

(4 of 4)

Page 60: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

60

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.22: DrawStarsForm.cs

2 // Using paths to draw stars on the form.

3 using System;

4 using System.Drawing;

5 using System.Drawing.Drawing2D;

6 using System.Windows.Forms;

7

8 // draws randomly colored stars

9 public partial class DrawStarsForm : Form

10 {

11 // default constructor

12 public DrawStarsForm()

13 {

14 InitializeComponent();

15 } // end constructor

16

17 // create path and draw stars along it

18 private void DrawStarsForm_Paint(object sender, PaintEventArgs e)

19 {

20 Graphics graphicsObject = e.Graphics;

21 Random random = new Random();

22 SolidBrush brush =

23 new SolidBrush( Color.DarkMagenta );

24

25 // x and y points of the path

26 int[] xPoints =

27 { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };

28 int[] yPoints =

29 { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };

30

Outline

DrawStarsForm.cs

(1 of 3)

Create two arrays of x and y points

where stars will be drawn

Page 61: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

61

2006 Pearson Education, Inc. All rights reserved.

31 // create graphics path for star;

32 GraphicsPath star = new GraphicsPath();

33

34 // create star from series of points

35 for ( int i = 0; i <= 8; i += 2 )

36 star.AddLine( xPoints[ i ], yPoints[ i ],

37 xPoints[ i + 1 ], yPoints[ i + 1 ] );

38

39 // close the shape

40 star.CloseFigure();

41

42 // translate the origin to (150, 150)

43 graphicsObject.TranslateTransform( 150, 150 );

44

45 // rotate the origin and draw stars in random colors

46 for ( int i = 1; i <= 18; i++ )

47 {

48 graphicsObject.RotateTransform( 20 );

49

50 brush.Color = Color.FromArgb(

51 random.Next( 200, 255 ), random.Next( 255 ),

52 random.Next( 255 ), random.Next( 255 ) );

53

54 graphicsObject.FillPath( brush, star );

55 } // end for

56 } // end method DrawStarsForm_Paint

57 } // end class DrawStarsForm

Outline

DrawStarsForm.cs

(2 of 3)

Translate to a new origin

Create a GraphicsPath object for a star

Create a star

Move to the next position on the form

The rotation angle in degrees

Draw rectangle with random color

Page 62: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

62

2006 Pearson Education, Inc. All rights reserved.

Outline

DrawStarsForm.cs

(3 of 3)

Page 63: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

63

2006 Pearson Education, Inc. All rights reserved.

17.10 Introduction to Multimedia

• Multimedia applications demand extraordinary computing power

– Today’s ultrafast processors make multimedia-based applications commonplace

Page 64: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

64

2006 Pearson Education, Inc. All rights reserved.

17.11 Loading, Displaying and Scaling Images

•Image’s static method FromFile – Loads an image from a file on the disk

• Graphics– Form’s CreateGraphics method

• Creates a Graphics object for drawing on the Form

– Graphic’s Clear method • Paint the entire Form in the current background color

– Graphic’s DrawImage method • If the width and height do not correspond to the image’s original

dimensions, the image is scaled to fit the new width and height

Page 65: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

65

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.23: DisplayLogoForm.cs

2 // Displaying and resizing an image

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // displays an image and allows the user to resize it

8 public partial class DisplayLogoForm : Form

9 {

10 private Image image = Image.FromFile( @"images\Logo.gif" );

11 private Graphics graphicsObject;

12

13 public DisplayLogoForm()

14 {

15 InitializeComponent();

16 graphicsObject = this.CreateGraphics();

17 }

18

Outline

DisplayLogoForm.cs

(1 of 3)

Load image from specified location

Page 66: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

66

2006 Pearson Education, Inc. All rights reserved.

19 // handle setButton Click event

20 private void setButton_Click( object sender, EventArgs e )

21 {

22 // get user input

23 int width = Convert.ToInt32( widthTextBox.Text );

24 int height = Convert.ToInt32( heightTextBox.Text );

25

26 // if dimensions specified are too large

27 // display problem

28 if ( width > 375 || height > 225 )

29 {

30 MessageBox.Show( " Height or Width too large" );

31 return;

32 } // end if

33

34 // clear the Form then draw the image

35 graphicsObject.Clear( this.BackColor );

36 graphicsObject.DrawImage( image, 5, 5, width, height );

37 } // end method setButton_Click

38 } // end class DisplayLogoForm

Outline

DisplayLogoForm.cs

(2 of 3)

Retrieve the height and width the image should be

scaled to

Draw image with the specified width and height

Page 67: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

67

2006 Pearson Education, Inc. All rights reserved.

Outline

DisplayLogoForm.cs

(3 of 3)

Page 68: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

68

2006 Pearson Education, Inc. All rights reserved.

17.12 Animating a Series of Images

• 2-D collision detection – Enables a program to detect whether two shapes

overlap or if a point is contained within a shape– Rectangle’s method Contains

• Useful for determining whether a point is inside a rectangular area

• Artifacts– Unintended visual abnormality in a graphical program

Page 69: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

69

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.24: LogoAnimator.cs

2 // Program that animates a series of images.

3 using System;

4 using System.Drawing;

5 using System.Windows.Forms;

6

7 // animates a series of 30 images

8 public partial class LogoAnimator : Form

9 {

10 private Image[] images = new Image[ 30 ];

11 private int count = -1;

12

13 // LogoAnimator constructor

14 public LogoAnimator()

15 {

16 InitializeComponent();

17

18 for ( int i = 0; i < 30; i++ )

19 images[ i ] = Image.FromFile( @"images\deitel" + i + ".gif" );

20

21 logoPictureBox.Image = images[ 0 ]; // display first image

22

23 // set PictureBox to be the same size as Image

24 logoPictureBox.Size = logoPictureBox.Image.Size;

25 } // end LogoAnimator constructor

26

Outline

LogoAnimator.cs

(1 of 2)

Store and load the images that will be displayed

Start by displaying the first image

Page 70: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

70

2006 Pearson Education, Inc. All rights reserved.

27 // event handler for timer's Tick event

28 private void timer_Tick( object sender, EventArgs e )

29 {

30 count = ( count + 1 ) % 30; // increment counter

31 logoPictureBox.Image = images[ count ]; // display next image

32 } // end method timer_Tick

33 } // end class LogoAnimator

Outline

LogoAnimator.cs

(2 of 2)For every Tick event, display the next image

Page 71: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

71

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 17.2

It is more efficient to load an animation’s frames as one image than to load each image separately. (A painting program, such as Adobe Photoshop®, or Jasc® Paint Shop Pro™, can be used to combine the animation’s frames into one image.) If the images are being loaded separately from the Web, each loaded image requires a separate connection to the site on which the images are stored; this process can result in poor performance.

Page 72: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

72

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.25 : ChessPiece.cs

2 // Class that represents chess piece attributes.

3 using System;

4 using System.Drawing;

5

6 // represents a chess piece

7 class ChessPiece

8 {

9 // define chess-piece type constants

10 public enum Types

11 {

12 KING,

13 QUEEN,

14 BISHOP,

15 KNIGHT,

16 ROOK,

17 PAWN

18 } // end enum Types

19

20 private int currentType; // this object's type

21 private Bitmap pieceImage; // this object's image

22

23 // default display location

24 private Rectangle targetRectangle =

25 new Rectangle( 0, 0, 75, 75 );

26

27 // construct piece

28 public ChessPiece( int type, int xLocation,

29 int yLocation, Bitmap sourceImage )

Outline

ChessPiece.cs

(1 of 2)

Enumeration for chess pieces

Define the image location on the chessboard

Page 73: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

73

2006 Pearson Education, Inc. All rights reserved.

30 {

31 currentType = type; // set current type

32 targetRectangle.X = xLocation; // set current x location

33 targetRectangle.Y = yLocation; // set current y location

34

35 // obtain pieceImage from section of sourceImage

36 pieceImage = sourceImage.Clone(

37 new Rectangle( type * 75, 0, 75, 75 ),

38 System.Drawing.Imaging.PixelFormat.DontCare );

39 } // end method ChessPiece

40

41 // draw chess piece

42 public void Draw( Graphics graphicsObject )

43 {

44 graphicsObject.DrawImage( pieceImage, targetRectangle );

45 } // end method Draw

46

47 // obtain this piece's location rectangle

48 public Rectangle GetBounds()

49 {

50 return targetRectangle;

51 } // end method GetBounds

52

53 // set this piece's location

54 public void SetLocation( int xLocation, int yLocation )

55 {

56 targetRectangle.X = xLocation;

57 targetRectangle.Y = yLocation;

58 } // end method SetLocation

59 } // end class ChessPiece

Outline

ChessPiece.cs

(2 of 2)Extract a sub-image that contains only the current

piece’s bitmap data

Draws the chess piece

Change the chess piece location

Page 74: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

74

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.26: ChessGame.cs

2 // Chess Game graphics code.

3 using System;

4 using System.Collections;

5 using System.Drawing;

6 using System.Windows.Forms;

7

8 // allows 2 players to play chess

9 public partial class ChessGame : Form

10 {

11 private ArrayList chessTile = new ArrayList(); // for tile images

12 private ArrayList chessPieces = new ArrayList(); // for chess pieces

13 private int selectedIndex = -1; // index for selected piece

14 private int[ , ] board = new int[ 8, 8 ]; // board array

15 private const int TILESIZE = 75; // chess tile size in pixels

16

17 // default constructor

18 public ChessGame()

19 {

20 // Required for Windows Form Designer support

21 InitializeComponent();

22 } // end constructor

Outline

ChessGame.cs

(1 of 11)

private instance variables representing the

chessboard and pieces

Page 75: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

75

2006 Pearson Education, Inc. All rights reserved.

23

24 // load tile bitmaps and reset game

25 private void ChessGame_Load( object sender, EventArgs e )

26 {

27 // load chess board tiles

28 chessTile.Add( Bitmap.FromFile( @"images\lightTile1.png" ) );

29 chessTile.Add( Bitmap.FromFile( @"images\lightTile2.png" ) );

30 chessTile.Add( Bitmap.FromFile( @"images\darkTile1.png" ) );

31 chessTile.Add( Bitmap.FromFile( @"images\darkTile2.png" ) );

32

33 ResetBoard(); // initialize board

34 Invalidate(); // refresh form

35 } // end method ChessGame_Load

36

37 // initialize pieces to start and rebuild board

38 private void ResetBoard()

39 {

40 int current = -1;

41 ChessPiece piece;

42 Random random = new Random();

43 bool light = false;

44 int type;

45

46 chessPieces.Clear(); // ensure empty arraylist

47

48 // load whitepieces image

49 Bitmap whitePieces =

50 ( Bitmap ) Image.FromFile( @"images\whitePieces.png" );

51

Outline

ChessGame.cs

(2 of 11)

Load the chess board tile images from a specified location

Load the images for the white chess pieces

Page 76: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

76

2006 Pearson Education, Inc. All rights reserved.

52 // load blackpieces image

53 Bitmap blackPieces =

54 ( Bitmap ) Image.FromFile( @"images\blackPieces.png" );

55

56 // set whitepieces to be drawn first

57 Bitmap selected = whitePieces;

58

59 // traverse board rows in outer loop

60 for ( int row = 0; row <= board.GetUpperBound( 0 ); row++ )

61 {

62 // if at bottom rows, set to black pieces images

63 if ( row > 5 )

64 selected = blackPieces;

65

66 // traverse board columns in inner loop

67 for ( int column = 0;

68 column <= board.GetUpperBound( 1 ); column++ )

69 {

70 // if first or last row, organize pieces

71 if ( row == 0 || row == 7 )

72 {

73 switch ( column )

74 {

75 case 0:

76 case 7: // set current piece to rook

77 current = ( int ) ChessPiece.Types.ROOK;

78 break;

79 case 1:

Outline

ChessGame.cs

(3 of 11)Load the images for the black chess pieces

Put the chess pieces in the appropriate position using a

switch statement

Page 77: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

77

2006 Pearson Education, Inc. All rights reserved.

80 case 6: // set current piece to knight

81 current = ( int ) ChessPiece.Types.KNIGHT;

82 break;

83 case 2:

84 case 5: // set current piece to bishop

85 current = ( int ) ChessPiece.Types.BISHOP;

86 break;

87 case 3: // set current piece to king

88 current = ( int ) ChessPiece.Types.KING;

89 break;

90 case 4: // set current piece to queen

91 current = ( int ) ChessPiece.Types.QUEEN;

92 break;

93 } // end switch

94

95 // create current piece at start position

96 piece = new ChessPiece( current,

97 column * TILESIZE, row * TILESIZE, selected );

98

99 chessPieces.Add( piece ); // add piece to arraylist

100 } // end if

101

102 // if second or seventh row, organize pawns

103 if ( row == 1 || row == 6 )

104 {

105 piece = new ChessPiece(

106 ( int ) ChessPiece.Types.PAWN,

107 column * TILESIZE, row * TILESIZE, selected );

108 chessPieces.Add( piece ); // add piece to arraylist

109 } // end if

Outline

ChessGame.cs

(4 of 11)

Add the pawns to its appropriate positions

Page 78: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

78

2006 Pearson Education, Inc. All rights reserved.

110

111 type = random.Next( 0, 2 ); // determine board piece type

112

113 if ( light ) // set light tile

114 {

115 board[ row, column ] = type;

116 light = false;

117 }

118 else // set dark tile

119 {

120 board[ row, column ] = type + 2;

121 light = true;

122 }

123 } // end for loop for columns

124

125 light = !light; // account for new row tile color switch

126 } // end for loop for rows

127 } // end method ResetBoard

128

129 // display board in form OnPaint event

130 private void ChessGame_Paint( object sender, PaintEventArgs e )

131 {

132 Graphics graphicsObject = e.Graphics; // obtain graphics object

133 graphicsObject.TranslateTransform( 0, 24 ); // adjust origin

134

Outline

ChessGame.cs

(5 of 11)

Shift the origin of the form by 24 pixels

Page 79: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

79

2006 Pearson Education, Inc. All rights reserved.

135 for ( int row = 0; row <= board.GetUpperBound( 0 ); row++ )

136 {

137 for ( int column = 0;

138 column <= board.GetUpperBound( 1 ); column++)

139 {

140 // draw image specified in board array

141 graphicsObject.DrawImage(

142 ( Image ) chessTile[ board[ row, column ] ],

143 new Point( TILESIZE * column, ( TILESIZE * row ) ) );

144 } // end for loop for columns

145 } // end for loop for rows

146 } // end method ChessGame_Paint

147

148 // return index of piece that intersects point

149 // optionally exclude a value

150 private int CheckBounds( Point point, int exclude )

151 {

152 Rectangle rectangle; // current bounding rectangle

153

154 for ( int i = 0; i < chessPieces.Count; i++ )

155 {

156 // get piece rectangle

157 rectangle = GetPiece( i ).GetBounds();

158

159 // check if rectangle contains point

160 if ( rectangle.Contains( point ) && i != exclude )

161 return i;

162 } // end for

163

Outline

ChessGame.cs

(6 of 11)

Draw the chessboard tiles

Determine if the specified point is contained in the

rectangles

Retrieve the piece’s rectangle

Page 80: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

80

2006 Pearson Education, Inc. All rights reserved.

164 return -1;

165 } // end method CheckBounds

166

167 // handle pieceBox paint event

168 private void pieceBox_Paint(

169 object sender, System.Windows.Forms.PaintEventArgs e )

170 {

171 // draw all pieces

172 for ( int i = 0; i < chessPieces.Count; i++ )

173 GetPiece( i ).Draw( e.Graphics );

174 } // end method pieceBox_Paint

175

176 // handle pieceBox MouseDown event

177 private void pieceBox_MouseDown(

178 object sender, System.Windows.Forms.MouseEventArgs e )

179 {

180 // determine selected piece

181 selectedIndex = CheckBounds( new Point( e.X, e.Y ), -1 );

182 } // end method pieceBox_MouseDown

183

184 // if piece is selected, move it

185 private void pieceBox_MouseMove(

186 object sender, System.Windows.Forms.MouseEventArgs e )

187 {

188 if ( selectedIndex > -1 )

189 {

190 Rectangle region = new Rectangle(

191 e.X - TILESIZE * 2, e.Y - TILESIZE * 2,

192 TILESIZE * 4, TILESIZE * 4 );

Outline

ChessGame.cs

(7 of 11)

Draw every chess piece

Determine if user selected a piece

Create a region of 2 tiles from every direction of the

mouse cursor

Page 81: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

81

2006 Pearson Education, Inc. All rights reserved.

193

194 // set piece center to mouse

195 GetPiece( selectedIndex ).SetLocation(

196 e.X - TILESIZE / 2, e.Y - TILESIZE / 2 );

197

198 pieceBox.Invalidate( region ); // refresh region

199 } // end if

200 } // end method pieceBox_MouseMove

201

202 // on mouse up deselect piece and remove taken piece

203 private void pieceBox_MouseUp( object sender, MouseEventArgs e )

204 {

205 int remove = -1;

206

207 // if chess piece was selected

208 if ( selectedIndex > -1 )

209 {

210 Point current = new Point( e.X, e.Y );

211 Point newPoint = new Point(

212 current.X - ( current.X % TILESIZE ),

213 current.Y - ( current.Y % TILESIZE ) );

214

215 // check bounds with point, exclude selected piece

216 remove = CheckBounds( current, selectedIndex );

217

218 // snap piece into center of closest square

219 GetPiece( selectedIndex ).SetLocation( newPoint.X, newPoint.Y );

220 selectedIndex = -1; // deselect piece

221

Outline

ChessGame.cs

(8 of 11)

Set and center the selected piece location to the mouse-

cursor position

Refresh only the specified region

Determine is there is a collision

Align the current piece to the closest square and

deselect it

Page 82: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

82

2006 Pearson Education, Inc. All rights reserved.

222 // remove taken piece

223 if ( remove > -1 )

224 chessPieces.RemoveAt( remove );

225 } // end if

226

227 pieceBox.Invalidate(); // ensure artifact removal

228 } // end method pieceBox_MouseUp

229

230 // helper function to convert 231 // ArrayList object to ChessPiece

232 private ChessPiece GetPiece( int i )

233 {

234 return ( ChessPiece ) chessPieces[ i ];

235 } // end method GetPiece

236

237 // handle NewGame menu option click

238 private void newGameItem_Click(

239 object sender, System.EventArgs e )

240 {

241 ResetBoard(); // reinitialize board

242 Invalidate(); // refresh form

243 } // end method newGameItem_Click

244 } // end class ChessGame

Outline

ChessGame.cs

(9 of 11)Refresh chessboard

Remove the selected piece

Page 83: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

83

2006 Pearson Education, Inc. All rights reserved.

Outline

ChessGame.cs

(10 of 11)

Page 84: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

84

2006 Pearson Education, Inc. All rights reserved.

Outline

ChessGame.cs

(11 of 11)

Page 85: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

85

2006 Pearson Education, Inc. All rights reserved.

17.13 Window Media Player

• Windows Media Player control – Type AxMediaPlayer

– Enables an application to play video and sound in many multimedia formats

– URL property • Specifies the file that Windows Media Player is currently

using

Page 86: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

86

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.27: MediaPlayerTest.cs

2 // Windows Media Player control used to play media files.

3 using System;

4 using System.Windows.Forms;

5

6 public partial class MediaPlayer : Form

7 {

8 // default constructor

9 public MediaPlayer()

10 {

11 InitializeComponent();

12 } // end constructor

13

14 // open new media file in Windows Media Player

15 private void openItem_Click( object sender, EventArgs e )

16 {

17 openMediaFileDialog.ShowDialog();

18

19 // load and play the media clip

20 player.URL = openMediaFileDialog.FileName;

21 } // end method openItem_Click

22

23 // exit program when exit menu item is clicked

24 private void exitItem_Click( object sender, EventArgs e )

25 {

26 Application.Exit();

27 } // end method exitItem_Click

28 } // end class MediaPlayer

Outline

MediaPlayerTest.cs

(1 of 2)

Allow the user to select a file

Specifies the file that Windows Media Player is using

Page 87: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

87

2006 Pearson Education, Inc. All rights reserved.

Outline

MediaPlayerTest.cs

(2 of 2)

Page 88: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

88

2006 Pearson Education, Inc. All rights reserved.

17.14 Microsoft Agent

• Microsoft Agent– Add interactive animated characters to Windows

applications or Web pages– Characters can speak and respond to user input

• Via speech recognition and synthesis– The control uses a speech recognition engine

• Translates vocal sound input from a microphone to language that the computer understands

– Programmers can even create their own animated characters, with the help from:• Microsoft Agent Character Editor • Microsoft Linguistic Sound Editing Tool

Page 89: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

89

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.28 | Peedy introducing himself when the window opens.

Bubble contains text equivalent to words Peedy

speaks

Page 90: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

90

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 17.1

Agent characters remain on top of all active windows while a Microsoft Agent application is running. Their motions are not limited by the boundaries of the browser or application window.

Page 91: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

91

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.29 | Peedy’s Pleased animation.

Page 92: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

92

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.30 | Peedy’s reaction when he is clicked.

Pointer clicking Peedy

Page 93: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

93

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.31 | Peedy flying animation.

Page 94: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

94

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.32 | Peedy waiting for speech input.

Pizza style options Tool tip indicates that Peedy is waiting for user input

Page 95: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

95

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.33 | Peedy repeating a request for Seattle-style pizza.

Tool tip indicates recognized speech

Page 96: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

96

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.34 | Peedy repeating a request for anchovies as an additional topping.

Page 97: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

97

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.35 | Peedy recounting the order.

Page 98: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

98

2006 Pearson Education, Inc. All rights reserved.

Fig. 17.36 | Peedy calculating the total.

Page 99: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

99

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 17.28: Agent.cs

2 // Microsoft Agent demonstration.

3 using System;

4 using System.Collections;

5 using System.Windows.Forms;

6 using System.IO;

7

8 public partial class Agent : Form

9 {

10 // current agent object

11 private AgentObjects.IAgentCtlCharacter speaker;

12

13 // default constructor

14 public Agent()

15 {

16 InitializeComponent();

17

18 // initialize the characters

19 try

20 {

21 // load characters into agent object

22 mainAgent.Characters.Load( "Genie",

23 @"C:\windows\msagent\chars\Genie.acs" );

24 mainAgent.Characters.Load( "Merlin",

25 @"C:\windows\msagent\chars\Merlin.acs" );

26 mainAgent.Characters.Load( "Peedy",

27 @"C:\windows\msagent\chars\Peedy.acs" );

28 mainAgent.Characters.Load( "Robby",

29 @"C:\windows\msagent\chars\Robby.acs" );

30

Outline

Agent.cs

(1 of 8)

Load Microsoft agents

Page 100: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

100

2006 Pearson Education, Inc. All rights reserved.

31 // set current character to Genie and show him

32 speaker = mainAgent.Characters[ "Genie" ];

33 GetAnimationNames(); // obtain an animation name list

34 speaker.Show( 0 ); // display Genie

35 characterCombo.SelectedText = "Genie";

36 } // end try

37 catch ( FileNotFoundException )

38 {

39 MessageBox.Show( "Invalid character location",

40 "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );

41 } // end catch

42 } // end constructor

43

44 // event handler for Speak Button

45 private void speakButton_Click( object sender, EventArgs e )

46 {

47 // if textbox is empty, have the character ask

48 // user to type the words into the TextBox; otherwise,

49 // have the character say the words in the TextBox

50 if ( speechTextBox.Text == "" )

51 speaker.Speak(

52 "Please, type the words you want me to speak", "" );

53 else

54 speaker.Speak( speechTextBox.Text, "" );

55 } // end method speakButton_Click

56

Outline

Agent.cs

(2 of 8)

Show and set default agent to Genie

Prompt user for an input for what he/she wants

the agent to say

Agent will speak the user’s input

Page 101: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

101

2006 Pearson Education, Inc. All rights reserved.

57 // event handler for Agent control's ClickEvent

58 private void mainAgent_ClickEvent(

59 object sender, AxAgentObjects._AgentEvents_ClickEvent e )

60 {

61 speaker.Play( "Confused" );

62 speaker.Speak( "Why are you poking me?", "" );

63 speaker.Play( "RestPose" );

64 } // end method mainAgent_ClickEvent

65

66 // ComboBox changed event, switch active agent character

67 private void characterCombo_SelectedIndexChanged(

68 object sender, EventArgs e )

69 {

70 ChangeCharacter( characterCombo.Text );

71 } // end method characterCombo_SelectedIndexChanged

72

73 // utility method to change characters

74 private void ChangeCharacter( string name )

75 {

76 speaker.StopAll( "Play" );

77 speaker.Hide( 0 );

78 speaker = mainAgent.Characters[ name ];

79

80 // regenerate animation name list

81 GetAnimationNames();

82 speaker.Show( 0 );

83 } // end method ChangeCharacter

Outline

Agent.cs

(3 of 8)

Stop current animation and plays specified animation

Switch Microsoft agent

Page 102: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

102

2006 Pearson Education, Inc. All rights reserved.

84

85 // get animation names and store in ArrayList

86 private void GetAnimationNames()

87 {

88 // ensure thread safety

89 lock ( this )

90 {

91 // get animation names

92 IEnumerator enumerator = mainAgent.Characters[

93 speaker.Name ].AnimationNames.GetEnumerator();

94

95 string voiceString;

96

97 // clear actionsCombo

98 actionsCombo.Items.Clear();

99 speaker.Commands.RemoveAll();

100

101 // copy enumeration to ArrayList

102 while ( enumerator.MoveNext() )

103 {

104 // remove underscores in speech string

105 voiceString = ( string ) enumerator.Current;

106 voiceString = voiceString.Replace( "_", "underscore" );

107

108 actionsCombo.Items.Add( enumerator.Current );

109

110 // add all animations as voice enabled commands

111 speaker.Commands.Add( ( string ) enumerator.Current,

112 enumerator.Current, voiceString, true, false );

113 } // end while

Outline

Agent.cs

(4 of 8)

Create an IEnumerator object to iterate through the

characters’ animations

Add a new command to the current character

Clear existing items

Page 103: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

103

2006 Pearson Education, Inc. All rights reserved.

114

115 // add custom command

116 speaker.Commands.Add( "MoveToMouse", "MoveToMouse",

117 "MoveToMouse", true, true );

118 } // end lock

119 } // end method GetAnimationNames

120

121 // user selects new action

122 private void actionsCombo_SelectedIndexChanged(

123 object sender, EventArgs e )

124 {

125 speaker.StopAll( "Play" );

126 speaker.Play( actionsCombo.Text );

127 speaker.Play( "RestPose" );

128 } // end method actionsCombo_SelectedIndexChanged

129

130 // event handler for Agent commands

131 private void mainAgent_Command(

132 object sender, AxAgentObjects._AgentEvents_CommandEvent e )

133 {

134 // get UserInput object

135 AgentObjects.IAgentCtlUserInput command =

136 ( AgentObjects.IAgentCtlUserInput ) e.userInput;

137

138 // change character if user speaks character name

139 if ( command.Voice == "Peedy" || command.Voice == "Robby" ||

140 command.Voice == "Merlin" || command.Voice == "Genie" )

141 {

142 ChangeCharacter( command.Voice );

143 return;

144 } // end if

Outline

Agent.cs

(5 of 8)

Stop current animation and play specified animation

Assign the userInput object to an IAgentCtlUserInput object to identify command

Add the “MoveToMouse” command to the agent

Page 104: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

104

2006 Pearson Education, Inc. All rights reserved.

145

146 // send agent to mouse

147 if ( command.Voice == "MoveToMouse" )

148 {

149 speaker.MoveTo( Convert.ToInt16( Cursor.Position.X - 60 ),

150 Convert.ToInt16( Cursor.Position.Y - 60 ), 5 );

151 return;

152 } // end if

153

154 // play new animation

155 speaker.StopAll( "Play" );

156 speaker.Play( command.Name );

157 }

158 } // end class Agent

Outline

Agent.cs

(6 of 8)Moves the agent to the specified screen position

Stop current animation and play specified animation

Page 105: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

105

2006 Pearson Education, Inc. All rights reserved.

Outline

Agent.cs

(7 of 8)

Genie performing Writing animation

Drop-down list from which you can choose a character animation

Writing animation selected

Tool tip indicating that Merlin is listening for a voice command

Merlin responding to user spoken animation command.

Tool tip shows the words that the speech recognition engine

translated to the application

Page 106: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

106

2006 Pearson Education, Inc. All rights reserved.

Outline

Agent.cs

(8 of 8)Text input

Peedy repeating the words entered by the user. Peedy’s speech can be heard through your computer’s speakers.

Robby responding to being clicked with the mouse pointer.

The commands pop-up window

Page 107: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

107

2006 Pearson Education, Inc. All rights reserved.

17.14 Microsoft Agent (Cont.)

• IAgentCtlCharacter– Represents the current character

– Method Play • Plays an animation

– Accepts a string representing one of the predefined animations for the character

– Method Speak• Receives a string that the character should speak

– Method MoveTo • Moves the character to the specified position on the screen

Page 108: 2006 Pearson Education, Inc. All rights reserved. 1 17 Graphics and Multimedia

108

2006 Pearson Education, Inc. All rights reserved.

17.14 Microsoft Agent (Cont.)

• Commands– Method Add

• Adds a new command to the command list– Property Commands

• List of valid commands that is contained in the IAgentCtlCharacter– Commands can be viewed in the Commands pop-up window

• Displays when the user right-clicks an Agent character

– Triggered when the user selects the command from the Commands pop-up window or speaks the voice input into a microphone

• Command logic is handled in the Command event handler of the AxAgent control

• When a user clicks a character, the AxAgent control’s ClickEvent event handler executes