97
2002 Prentice Hall. All rights reserved. 1 Chapter 16 – Graphics and Multimedia Outline 只只 16.3 16.1 Introduction 16.2 Graphics Contexts and Graphics Objects16.3 Color Control 16.4 Font Control 16.5 Drawing Lines, Rectangles and Ovals 16.6 Drawing Arcs 16.7 Drawing Polygons and Polylines 16.8 Advanced Graphics Capabilities 16.9 Introduction to Multimedia 16.10 Loading, Displaying and Scaling Images 16.11 Animating a Series of Images 16.12 Windows Media Player 16.13 Microsoft Agent

Chapter 16 – Graphics and Multimedia

  • Upload
    kata

  • View
    50

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 16 – Graphics and Multimedia. Outline 只教 16.3 - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

1

Chapter 16 – Graphics and Multimedia

Outline 只教 16.316.1 Introduction16.2   Graphics Contexts and Graphics Objects16.3  Color Control16.4   Font Control16.5   Drawing Lines, Rectangles and Ovals16.6   Drawing Arcs16.7   Drawing Polygons and Polylines16.8   Advanced Graphics Capabilities16.9   Introduction to Multimedia16.10  Loading, Displaying and Scaling Images16.11  Animating a Series of Images16.12  Windows Media Player16.13  Microsoft Agent

Page 2: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

2

16.1 Introduction

• GDI+– extension of the Graphical Device Interface– System.Drawing and System.Drawing.Drawing2D

• Class Graphics– Various methods for drawing on a Control– Requires a Pen (shape outlines) or Brush (solid objects)

• Structure Color• Font and FontFamily classes

Page 3: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

3

16.1 Introduction

Fig. 16.1 System.Drawing namespace’s Classes and Structures.

System.Drawing

Bitmap

Font  

FontFamily

Graphics

Icon

Pen

Region

SolidBrush

TextureBrush

Image

SolidBrush

HatchBrush

LinearGradient

PathGradient

SolidBrush

TextureBrush

class

Structure

Color

Point

Rectangle

Size

KeySystem.Drawing

Bitmap

Font  

FontFamily

Graphics

Icon

Pen

Region

SolidBrush

TextureBrush

Image

SolidBrush

HatchBrush

LinearGradient

PathGradient

SolidBrush

TextureBrush

Class

Structure

Color

Point

Rectangle

Size

Key

Page 4: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

4

16.1 Introduction

• GDI+’s coordinate system– Upper-left corner of component has coordinates (0, 0)

– Coordinate pairs• Allow positioning of text and shapes

• Horizontal coordinate (x-coordinate)

– Distance to the right from upper-left corner

• Vertical coordinate (y-coordinate)

– Distance down from upper-left corner

– Coordinate units measured in pixels

– Used with structures Rectangle and Point

Page 5: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

5

16.1 Introduction

Fig. 16.2 GDI+ coordinate system. Units are measured in pixels.

  

 

x-axis

y-axis

(x, y)

+x

+y

(0, 0)

Page 6: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

6

16.2 Graphics Contexts and Graphics Objects

• Graphics context– Represents drawing surface

– Managed using a Graphics object

• Overridable OnPaint method– Inherited by every Form– Performs most graphics operations

– Takes PaintEventArgs object as argument• Graphics property contains Graphics object

– Triggers Control’s Paint event

Page 7: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

7

16.2 Graphics Contexts and Graphics Objects

• Paint event handler versus overriding OnPaint– Painting as an event-driven process

– Calling method Invalidate instead of OnPaint• Passing Rectangle argument to Invalidate

• Graphics contexts for Controls– Each Control has its own graphics context

• Method CreateGraphics

Page 8: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

8

16.3 Color Control

• Structure Color– ARGB values

• Alpha, red, green and blue values, respectively

• Each value represented as a Byte• A, R, G, B properties

• Alpha value determines intensity

– 0 = transparent, 255 = opaque color

– Alpha blending of RGB value and background color• FromArgb method

– Shared Color constants• Color names representing RGB values (A = 255)• FromName method

Page 9: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

9

16.3 Color Control

Constants in structure Color (all are Public Shared)

RGB value Constants in structure Color (all are Public Shared)

RGB value

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

Pink 255, 175, 175 Gray 28, 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 Fig. 16.3 Color structure Shared constants and their RGB values.

Page 10: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

10

16.3 Color Control

Structure Color methods and properties

Description

Common Methods

Shared FromArgb Creates a color based on red, green and blue values expressed as Integers from 0 to 255. Overloaded version allows specification of alpha, red, green and blue values.

Shared FromName Creates a color from a name, passed as a String. Common Properties A Integer between 0 and 255, representing the alpha component. R Integer between 0 and 255, representing the red component. G Integer between 0 and 255, representing the green component. B Integer between 0 and 255, representing the blue component. Fig. 16.4 Color structure members.

Page 11: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

11

16.3 Color Control

• Pen objects– Used to draw lines

– Constructors allow specification of color and drawing width– Pens collection (System.Drawing) contains predefined Pens

• Brush objects– Used to color interiors of shapes

– Abstract class

– Various derived classes for fill styles

– Upcoming example: Color value and alpha demonstration

Page 12: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

12

16.3 Color Control

Class Description HatchBrush Uses a rectangular brush to fill 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 into 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. Defined by a Color object. TextureBrush Fills a region by repeating a specified Image across the surface. Fig. 16.5 Classes that derive from class Brush.

Page 13: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline13

ShowColors.vb

1 ' Fig. 16.6: ShowColors.vb2 ' Using different colors in Visual Basic.3 4 Public Class FrmColorForm5 Inherits System.Windows.Forms.Form6 7 ' input text boxes8 Friend WithEvents txtColorName As TextBox9 Friend WithEvents txtGreenBox As TextBox10 Friend WithEvents txtRedBox As TextBox11 Friend WithEvents txtAlphaBox As TextBox12 Friend WithEvents txtBlueBox As TextBox13 14 ' set color command buttons15 Friend WithEvents cmdColorName As Button16 Friend WithEvents cmdColorValue As Button17 18 ' color labels19 Friend WithEvents lblBlue As Label20 Friend WithEvents lblGreen As Label21 Friend WithEvents lblRed As Label22 Friend WithEvents lblAlpha As Label23 24 ' group boxes25 Friend WithEvents nameBox As GroupBox26 Friend WithEvents colorValueGroup As GroupBox27 28 ' Visual Studio .NET generated code29 30 ' color for back rectangle31 Private mBehindColor As Color = Color.Wheat32 33 ' color for front rectangle34 Private mFrontColor As Color = Color.FromArgb(100, 0, 0, 255)35

Page 14: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline14

ShowColors.vb

36 ' overrides Form OnPaint method37 Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)38 Dim graphicsObject As Graphics = e.Graphics ' get graphics39 40 Dim textBrush As SolidBrush = _41 New SolidBrush(Color.Black) ' create text brush42 43 Dim brush As SolidBrush = _44 New SolidBrush(Color.White) ' create solid brush45 46 ' draw white background47 graphicsObject.FillRectangle(brush, 4, 4, 275, 180)48 49 ' display name of behindColor50 graphicsObject.DrawString(mBehindColor.Name, Me.Font, _51 textBrush, 40, 5)52 53 ' set brush color and display back rectangle54 brush.Color = mBehindColor55 56 graphicsObject.FillRectangle(brush, 45, 20, 150, 120)57 58 ' display Argb values of front color59 graphicsObject.DrawString("Alpha: " & mFrontColor.A & _60 " Red: " & mFrontColor.R & " Green: " & mFrontColor.G _61 & " Blue: " & mFrontColor.B, Me.Font, textBrush, _62 55, 165)63 64 ' set brush color and display front rectangle65 brush.Color = mFrontColor66 67 graphicsObject.FillRectangle(brush, 65, 35, 170, 130)68 End Sub ' OnPaint69

Creates a black and white SolidBrush for drawing on the form

Gets a reference to PaintEventArgs e’s Graphics object and assigns it to Graphics object graphicsObject

Graphics method FillRectangle draws a solid white rectangle with the Brush supplied as a parameter

Assigns the ColormBehindColor value to the Brush’s Color property and displays a rectangle

Page 15: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline15

ShowColors.vb

70 ' handle cmdColorValue click event71 Private Sub cmdColorValue_Click(ByVal sender As _72 System.Object, ByVal e As System.EventArgs) _73 Handles cmdColorValue.Click74 75 ' obtain new front color from text boxes76 mFrontColor = Color.FromArgb(txtAlphaBox.Text, _77 txtRedBox.Text, txtGreenBox.Text, txtBlueBox.Text)78 79 Invalidate() ' refresh Form80 End Sub ' cmdColorValue_Click81 82 Private Sub cmdColorName_Click(ByVal sender As _83 System.Object, ByVal e As System.EventArgs) _84 Handles cmdColorName.Click85 86 ' set behindColor to color specified in text box87 mBehindColor = Color.FromName(txtColorName.Text)88 89 Invalidate() ' refresh Form90 End Sub ' cmdColorName_Click91 92 End Class ' FrmColorForm

Page 16: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline16

ShowColors.vb

Page 17: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline17

ShowColorsComplex.vb

1 ' Fig. 16.7: ShowColorsComplex.vb2 ' Change the background and text colors of a form.3 4 Imports System.Windows.Forms5 6 Public Class FrmColorDialogTest7 Inherits System.Windows.Forms.Form8 9 Friend WithEvents cmdBackgroundButton As Button10 Friend WithEvents cmdTextButton As Button11 12 ' Visual Studio .NET generated code13 14 ' change text color15 Private Sub cmdTextButton_Click (ByVal sender As System.Object, _16 ByVal e As System.EventArgs) Handles cmdTextButton.Click17 18 ' create ColorDialog object19 Dim colorBox As ColorDialog = New ColorDialog()20 Dim result As DialogResult21 22 ' get chosen color23 result = colorBox.ShowDialog()24 25 If result = DialogResult.Cancel Then26 Return27 End If28 29 ' assign forecolor to result of dialog30 cmdBackgroundButton.ForeColor = colorBox.Color31 cmdTextButton.ForeColor = colorBox.Color32 End Sub ' cmdTextButton_Click33

Define Button cmdTextButton’s event handler

Creates new ColorDialog named colorBox and invokes ShowDialog method to display the window

Sets the text color of both buttons to the selected color

Page 18: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline18

ShowColorsComplex.vb

34 ' change background color35 Private Sub cmdBackgroundButton_Click( _36 ByVal sender As System.Object, _37 ByVal e As System.EventArgs) _38 Handles cmdBackgroundButton.Click39 40 ' create ColorDialog object41 Dim colorBox As ColorDialog = New ColorDialog()42 Dim result As DialogResult43 44 ' show ColorDialog and get result45 colorBox.FullOpen = True46 result = colorBox.ShowDialog()47 48 If result = DialogResult.Cancel Then49 Return50 End If51 52 ' set background color53 Me.BackColor = colorBox.Color54 End Sub ' cmdBackgroundButton_Click55 56 End Class ' FrmColorDialogTest

Defines the event handler for button cmdBackgroundButton

Sets the dialog’s FullOpen property to True

Page 19: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline19

ShowColorsComplex.vb

Page 20: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

20

16.4 Font Control

• Fonts– After a Font is created, its properties cannot be modified– Programmers must create a new Font object to be different

• Font constructors– Must require a font name as an argument– They usually require the font size as an argument– And usually require the font style

• Font metrics– Height– Descent (the amount that characters dip below the baseline)– Ascent (the amount that characters rise above the baseline)– Leading (difference between ascent of one line and descent

of the previous line)

Page 21: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

21

16.4 Font Control

Property Description Bold Tests a font for a bold font style. Returns True if the font is bold.

FontFamily Represents the FontFamily of the Font (a grouping structure to organize fonts and define their similar properties).

Height Represents the height of the font. Italic Tests a font for an italic font style. Returns True if the font is italic. Name Represents the font’s name as a String. Size Returns a Single value indicating the current font size measured in

design units (design units are any specified units of measurement for the font).

SizeInPoints Returns a Single value indicating the current font size measured in points.

Strikeout Tests a font for a strikeout font style. Returns True if the font is in strikeout format.

Underline Tests a font for a underline font style. Returns True if the font is underlined.

Fig. 16.8 Font class read-only properties.

Page 22: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline22

UsingFonts.vb

1 ' Fig. 16.9: UsingFonts.vb2 ' Demonstrating various font settings.3 4 Public Class FrmFonts5 Inherits System.Windows.Forms.Form6 7 ' Visual Studio .NET generated code8 9 ' demonstrate various font and style settings10 Protected Overrides Sub OnPaint( _ 11 ByVal paintEvent As PaintEventArgs)12 13 Dim graphicsObject As Graphics = paintEvent.Graphics14 Dim brush As SolidBrush = New SolidBrush(Color.DarkBlue)15 16 ' arial, 12 pt bold17 Dim style As FontStyle = FontStyle.Bold18 Dim arial As Font = New Font( _19 New FontFamily("Arial"), 12, style)20 21 ' times new roman, 12 pt regular22 style = FontStyle.Regular23 Dim timesNewRoman As Font = New Font( _24 "Times New Roman", 12, style)25 26 ' courier new, 16 pt bold and italic27 style = FontStyle.Bold Or FontStyle.Italic28 Dim courierNew As Font = New Font("Courier New", _29 16, style)30 31 ' tahoma, 18 pt strikeout32 style = FontStyle.Strikeout33 Dim tahoma As Font = New Font("Tahoma", 18, style)34

Font constructor initializes Font objects

Creates a DarkBlue SolidBrush object (brush), causing all strings drawn with that brush to appear in DarkBlue

Page 23: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline23

UsingFonts.vb

35 graphicsObject.DrawString(arial.Name & " 12 point bold.", _36 arial, brush, 10, 10)37 38 graphicsObject.DrawString(timesNewRoman.Name & _39 " 12 point plain.", timesNewRoman, brush, 10, 30)40 41 graphicsObject.DrawString(courierNew.Name & _42 " 16 point bold and italic.", courierNew, brush, 10, 54 )43 44 graphicsObject.DrawString(tahoma.Name & _45 " 18 point strikeout.", tahoma, brush, 10, 75)46 End Sub ' OnPaint47 48 End Class ' FrmFonts

Page 24: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

24

16.4 Font Control

Fig. 16.10 An illustration of font metrics.

Page 25: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

25

16.4 Font Control

Method Description GetCellAscent Returns an Integer representing the ascent of a font as measured

in design units.

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

GetEmHeight Returns an Integer representing the height of a font as measured in design points.

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

Fig. 16.11 FontFamily methods that return font-metric information.

Page 26: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline26

UsingFontMetrics.vb

1 ' Fig. 16.12: UsingFontMetrics.vb2 ' Displaying font metric information.3 4 Imports System5 Imports System.Drawing6 Imports System.Drawing.Text7 8 Public Class FrmFontMetrics9 Inherits System.Windows.Forms.Form10 11 ' Visual Studio .NET generated code12 13 Protected Overrides Sub OnPaint( _14 ByVal paintEvent As PaintEventArgs)15 16 Dim graphicsObject As Graphics = paintEvent.Graphics17 Dim brush As SolidBrush = New SolidBrush(Color.Red)18 Dim pen As Pen = New Pen(brush, Convert.ToSingle(2.5))19 20 ' Arial font metrics21 Dim arial As Font = New Font("Arial", 12)22 Dim family As FontFamily = arial.FontFamily23 Dim sanSerif As Font = New Font("Microsoft Sans Serif", _24 14, FontStyle.Italic)25 26 pen.Color = brush.Color27 brush.Color = Color.DarkBlue28 29 ' display Arial font metrics30 graphicsObject.DrawString("Current Font: " & arial.ToString, _31 arial, brush, 10, 10)32 33 graphicsObject.DrawString("Ascent: " & _ 34 family.GetCellAscent(FontStyle.Regular), arial, brush, _35 10, 30)36

Creates Font arial and sets it to 12 point Arial font

Uses class Font property FontFamily to obtain objects arial’s FontFamily object

Page 27: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline27

UsingFontMetrics.vb

37 graphicsObject.DrawString("Descent: " & _38 family.GetCellDescent(FontStyle.Regular), arial, brush, _ 39 10, 50)40 41 graphicsObject.DrawString("Height: " & _42 family.GetEmHeight(FontStyle.Regular), _43 arial, brush, 10, 70)44 45 graphicsObject.DrawString("Leading: " & _46 family.GetLineSpacing(FontStyle.Regular), arial, brush, _47 10, 90)48 49 ' display Sans Serif font metrics50 family = sanSerif.FontFamily51 52 graphicsObject.DrawString("Current Font: " & _53 sanSerif.ToString(), sanSerif, brush, 10, 130)54 55 graphicsObject.DrawString("Ascent: " & _56 family.GetCellAscent(FontStyle.Italic), _57 sanSerif, brush, 10, 150)58 59 graphicsObject.DrawString("Descent: " & _60 family.GetCellDescent(FontStyle.Italic), sanSerif, _ 61 brush, 10, 170)62 63 graphicsObject.DrawString("Height: " & family.GetEmHeight _64 (FontStyle.Italic), sanSerif, brush, 10, 190)65 66 graphicsObject.DrawString("Leading: " & _67 family.GetLineSpacing(FontStyle.Italic), sanSerif, _ 68 brush, 10, 210)69 End Sub ' OnPaint70 71 End Class ' FrmFontMetrics

Uses methods of class FontFamily to return integers specifying the ascent, descent, height and leading of the font

Page 28: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline28

UsingFontMetrics.vb

Page 29: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

29

16.5 Drawing Lines, Rectangles and Ovals

• Drawing shape outlines– Versions that take a Pen and four Integers are used

• Drawing solid shapes– Versions that take a Brush and four Integers

• Integer arguments– First two represent the coordinates of the upper-left corner of

the shape or its enclosing area

– Last two indicate the shape’s width and height

Page 30: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

30

16.5 Drawing Lines, Rectangles and Ovals

Graphics Drawing Methods and Descriptions Note: Many of these methods are overloaded—consult the documentation for a full listing.

DrawLine(ByVal p As Pen, ByVal x1 As Integer, ByVal y1 As Integer, ByVal x2 As Integer, ByVal y2 As Integer) Draws a line from (x1, y1) to (x2, y2). The Pen determines the color, style and width of the line. DrawRectangle(ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) 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 color, style, and border width of the rectangle. FillRectangle(ByVal b As Brush, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) 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(ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) Draws an ellipse inside a rectangle. The width and height of the rectangle are as specified, and its top-left corner is at point (x, y). The Pen determines the color, style and border width of the ellipse. FillEllipse(ByVal b As Brush, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) Draws a filled ellipse inside a rectangle. The width and height of the rectangle are as specified, and its top-left corner is at point (x, y). The Brush determines the pattern inside the ellipse. Fig. 16.13 Graphics methods that draw lines, rectangles and ovals.

Page 31: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline31

LinesRectanglesOvals.vb

1 ' Fig. 16.14: LinesRectanglesOvals.vb2 ' Demonstrating lines, rectangles, and ovals.3 4 Public Class FrmDrawing5 Inherits System.Windows.Forms.Form6 7 ' Visual Studio .NET generated code8 9 ' display ovals lines, and rectangles10 Protected Overrides Sub OnPaint( _11 ByVal paintEvent As PaintEventArgs)12 13 ' get graphics object14 Dim g As Graphics = paintEvent.Graphics15 Dim brush As SolidBrush = New SolidBrush(Color.Blue)16 Dim pen As Pen = New Pen(Color.AliceBlue)17 18 ' create filled rectangle19 g.FillRectangle(brush, 90, 30, 150, 90)20 21 ' draw lines to connect rectangles22 g.DrawLine(pen, 90, 30, 110, 40)23 g.DrawLine(pen, 90, 120, 110, 130)24 g.DrawLine(pen, 240, 30, 260, 40)25 g.DrawLine(pen, 240, 120, 260, 130)26 27 ' draw top rectangle28 g.DrawRectangle(pen, 110, 40, 150, 90)29 30 ' set brush to red31 brush.Color = Color.Red32 33 ' draw base Ellipse34 g.FillEllipse(brush, 280, 75, 100, 50)35

Method DrawLine takes a Pen and two pairs of Integers, specifying the start and endpoint of the line

Methods DrawRectangle and FillRectangle draw rectangles on the screen

Page 32: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline32

LinesRectanglesOvals.vb

36 ' draw connecting lines37 g.DrawLine(pen, 380, 55, 380, 100)38 g.DrawLine(pen, 280, 55, 280, 100)39 40 ' draw Ellipse outline41 g.DrawEllipse(pen, 280, 30, 100, 50)42 End Sub ' OnPaint43 44 End Class ' FrmDrawing

Page 33: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

33

16.5 Drawing Lines, Rectangles and Ovals

Fig. 16.15 Ellipse bounded by a rectangle.

height

width

(x, y)

Page 34: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

34

16.6 Drawing Arcs

• Arcs– Arcs are portions of ellipses

– Measured in degrees, beginning at the starting angle and continuing for a specified number of degrees, the arc angle

– An arc is said to sweep (traverse) its arc angle, beginning from its starting angle

– Measuring• Sweep in a clockwise direction, measured in positive degrees

• Sweep in a counterclockwise direction, measured in negative degrees

– Graphics methods used to draw arcs• DrawArc, DrawPie, and FillPie

Page 35: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

35

16.6 Drawing Arcs

Fig. 16.16 Positive and negative arc angles.

Positive angles

90° 90°

270°270°

0°180°0°180°

Negative angles

Page 36: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

36

16.6 Drawing Arcs

Graphics Methods And Descriptions Note: Many of these methods are overloaded—consult the documentation for a full listing. DrawArc(ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal startAngle As Integer, ByVal sweepAngle As Integer) Draws an arc of an ellipse, beginning from angle startAngle (in degrees) and sweeping sweepAngle degrees. The ellipse is defined by a bounding rectangle of width w, height h and upper-left corner (x,y). The Pen determines the color, border width and style of the arc. DrawPie(ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal startAngle As Integer, ByVal sweepAngle As Integer) 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 w, height h and upper-left corner (x,y). The Pen determines the color, border width and style of the arc. FillPie(ByVal b As Brush, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal startAngle As Integer, ByVal sweepAngle As Integer) Functions similarly to DrawPie, except draws a solid arc (i.e., a sector). The Brush determines the fill pattern for the solid arc. Fig. 16.17 Graphics methods for drawing arcs.

Page 37: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline37

DrawArcs.vb

1 ' Fig. 16.18: DrawArcs.vb2 ' Drawing various arcs on a form.3 4 Public Class FrmArcTest5 Inherits System.Windows.Forms.Form6 7 ' Visual Studio .NET generated code8 9 Protected Overrides Sub OnPaint( _10 ByVal paintEvent As PaintEventArgs)11 12 ' get graphics object13 Dim graphicsObject As Graphics = paintEvent.Graphics14 Dim rectangle1 As Rectangle = New Rectangle(15, 35, 80, 80)15 Dim brush1 As SolidBrush = New SolidBrush(Color.FireBrick)16 Dim pen1 As Pen = New Pen(brush1, 1)17 Dim brush2 As SolidBrush = New SolidBrush(Color.DarkBlue)18 Dim pen2 As Pen = New Pen(brush2, 1)19 20 ' start at 0 and sweep 360 degrees21 graphicsObject.DrawRectangle(pen1, rectangle1)22 graphicsObject.DrawArc(pen2, rectangle1, 0, 360)23 24 ' start at 0 and sweep 110 degrees25 rectangle1.Location = New Point(100, 35)26 graphicsObject.DrawRectangle(pen1, rectangle1)27 graphicsObject.DrawArc(pen2, rectangle1, 0, 110)28 29 ' start at 0 and sweep -270 degrees30 rectangle1.Location = New Point(185, 35)31 graphicsObject.DrawRectangle(pen1, rectangle1)32 graphicsObject.DrawArc(pen2, rectangle1, 0, -270)33

Creates the objects needed to draw various arcs

Draws a rectangle and then an arc inside the rectangle

Changes the location of the Rectangle by setting its Location property to a new Point

Page 38: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline38

DrawArcs.vb

34 ' start at 0 and sweep 360 degrees35 rectangle1.Location = New Point(15, 120)36 rectangle1.Size = New Size(80, 40)37 graphicsObject.DrawRectangle(pen1, rectangle1)38 graphicsObject.FillPie(brush2, rectangle1, 0, 360)39 40 ' start at 270 and sweep -90 degrees41 rectangle1.Location = New Point(100, 120)42 graphicsObject.DrawRectangle(pen1, rectangle1)43 graphicsObject.FillPie(brush2, rectangle1, 270, -90)44 45 ' start at 0 and sweep -270 degrees46 rectangle1.Location = New Point(185, 120)47 graphicsObject.DrawRectangle(pen1, rectangle1)48 graphicsObject.FillPie(brush2, rectangle1, 0, -270)49 End Sub ' OnPaint50 51 End Class ' FrmArcTest

Sets the Size property to a new Size object

Page 39: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

39

16.7 Drawing Polygons and Polylines

• Polygons– Multisided shapes– Graphics methods used to draw polygons

• DrawLines, DrawPolygon, and FillPolygon

Page 40: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

40

16.7 Drawing Polygons and Polylines

Method Description DrawLines Draws a series of connected lines. The coordinates of each point are

specified in an array of Points. 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. This method draws a closed polygon, even if the last point is different from the first point.

FillPolygon Draws a solid polygon. The coordinates of each point are specified in an array of Points. This method draws a closed polygon, even if the last point is different from the first point.

Fig. 16.19 Graphics methods for drawing polygons.

Page 41: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline41

DrawPolygons.vb

1 ' Fig. 16.20: DrawPolygons.vb2 ' Demonstrating polygons.3 4 Public Class FrmPolygon5 Inherits System.Windows.Forms.Form6 7 ' polygon type options8 Friend WithEvents filledPolygonRadio As RadioButton9 Friend WithEvents lineRadio As RadioButton10 Friend WithEvents polygonRadio As RadioButton11 12 ' command buttons13 Friend WithEvents cmdClear As Button14 Friend WithEvents cmdNewColor As Button15 16 Friend WithEvents drawWindow As Panel17 Friend WithEvents typeGroup As GroupBox18 19 ' Visual Studio .NET generated code20 21 ' contains list of polygon points 22 Private mPoints As ArrayList = New ArrayList()23 24 ' initialize default pen and brush25 Dim mPen As Pen = New Pen(Color.DarkBlue)26 Dim mBrush As SolidBrush = New SolidBrush(Color.DarkBlue)27 28 ' draw panel mouse down event handler29 Private Sub drawWindow_MouseDown(ByVal sender _30 As Object, ByVal e As _31 System.Windows.Forms.MouseEventArgs) _32 Handles drawWindow.MouseDown33

Declares the Pen and Brush used to color our shapes

Declaring ArrayList mPoints as a container for our Point objects allows the user to specify a variable number of points

Page 42: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline42

DrawPolygons.vb

34 ' Add mouse position to vertex list35 mPoints.Add(New Point(e.X, e.Y))36 drawWindow.Invalidate() ' refresh panel37 End Sub ' drawWindow_MouseDown38 39 ' draw panel paint event handler40 Private Sub drawWindow_Paint(ByVal sender As Object, _41 ByVal e As System.Windows.Forms.PaintEventArgs) _42 Handles drawWindow.Paint43 44 ' get graphics object for panel45 Dim graphicsObject As Graphics = e.Graphics46 47 ' if arraylist has 2 or more points, display shape48 If mPoints.Count > 1 Then49 50 ' get array for use in drawing functions51 Dim pointArray() As Point = _52 mPoints.ToArray(mPoints(0).GetType())53 54 If polygonRadio.Checked Then ' draw polygon55 graphicsObject.DrawPolygon(mPen, pointArray)56 57 ElseIf lineRadio.Checked Then ' draw lines58 graphicsObject.DrawLines(mPen, pointArray)59 60 ElseIf filledPolygonRadio.Checked Then ' draw filled61 graphicsObject.FillPolygon(mBrush, pointArray)62 End If63 64 End If65 66 End Sub ' drawWindow_Paint67

Extracts an Array from the ArrayList via method ToArray

Page 43: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline43

DrawPolygons.vb

68 ' handle cmdClear click event69 Private Sub cmdClear_Click(ByVal sender As System.Object, _70 ByVal e As System.EventArgs) Handles cmdClear.Click71 72 mPoints = New ArrayList() ' remove points73 74 drawWindow.Invalidate() ' refresh panel75 End Sub ' cmdClear_Click76 77 ' handle polygon radio button CheckedChange event78 Private Sub polygonRadio_CheckedChanged(ByVal sender As _79 System.Object, ByVal e As System.EventArgs) _80 Handles polygonRadio.CheckedChanged81 82 drawWindow.Invalidate() ' refresh panel83 End Sub ' polygonRadio_CheckedChanged84 85 ' handle line radio button CheckChanged event86 Private Sub lineRadio_CheckedChanged(ByVal sender As _87 System.Object, ByVal e As System.EventArgs) _88 Handles lineRadio.CheckedChanged89 90 drawWindow.Invalidate() ' refresh panel91 End Sub ' lineRadio_CheckedChanged92 93 ' handle filled polygon radio button CheckChanged event94 Private Sub filledPolygonRadio_CheckedChanged(ByVal sender _95 As System.Object, ByVal e As System.EventArgs) _96 Handles filledPolygonRadio.CheckedChanged97 98 drawWindow.Invalidate() ' refresh panel99 End Sub ' filledPolygonRadio_CheckedChanged100

Page 44: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline44

DrawPolygons.vb

101 ' handle cmdNewColor click event102 Private Sub cmdNewColor_Click(ByVal sender As _103 System.Object, ByVal e As System.EventArgs) _104 Handles cmdNewColor.Click105 106 ' create new color dialog107 Dim colorBox As ColorDialog = New ColorDialog()108 109 ' show dialog and obtain result110 Dim result As DialogResult = colorBox.ShowDialog()111 112 ' return if user cancels113 If result = DialogResult.Cancel Then114 Return115 End If116 117 mPen.Color = colorBox.Color ' set pen to new color118 mBrush.Color = colorBox.Color ' set brush119 drawWindow.Invalidate() ' refresh panel120 End Sub ' cmdNewColor_Click121 122 End Class ' FrmPolygon

Page 45: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline45

DrawPolygons.vb

Page 46: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

46

16.8 Advanced Graphics Capabilities

• Visual Basic offers many additional graphics capabilities

• Examples– Brush hierarchy also includes:

• HatchBrush, LinearGradientBrush, PathGradientBrush and TextureBrush

– Additional graphics features• Dashed lines, thick lines, filling shapes with patterns, etc

– General path• A shape constructed from straight lines and complex curves

Page 47: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline47

DrawShapes.vb

1 ' Fig. 16.21: DrawShapes.vb2 ' Drawing various shapes on a form.3 4 Imports System.Drawing.Drawing2D5 6 Public Class FrmDrawShapes7 Inherits System.Windows.Forms.Form8 9 ' Visual Studio .NET generated code10 11 ' draw various shapes on form12 Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)13 14 ' references to object we will use15 Dim graphicsObject As Graphics = e.Graphics16 17 ' ellipse rectangle and gradient brush18 Dim drawArea1 As Rectangle = New Rectangle(5, 35, 30, 100)19 Dim linearBrush As LinearGradientBrush = _20 New LinearGradientBrush(drawArea1, Color.Blue, _21 Color.Yellow, LinearGradientMode.ForwardDiagonal)22 23 ' pen and location for red outline rectangle24 Dim thickRedPen As Pen = New Pen(Color.Red, 10)25 Dim drawArea2 As Rectangle = New Rectangle(80, 30, 65, 100)26 27 ' bitmap texture28 Dim textureBitmap As Bitmap = New Bitmap(10, 10)29 Dim graphicsObject2 As Graphics = _30 Graphics.FromImage(textureBitmap) ' get bitmap graphics31 32 ' brush and pen used throughout program33 Dim solidColorBrush As SolidBrush = _34 New SolidBrush(Color.Red)35 Dim coloredPen As Pen = New Pen(solidColorBrush)

Creates LinearGradientBrush object Brush

Creates a Pen object pen, and passes arguments Color.Red and Integer 10, indicating that we want pen

to draw red lines that are 10 pixels wide

Creates a new Bitmap image, which is initially empty

Page 48: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline48

DrawShapes.vb

36 37 ' draw ellipse filled with a blue-yellow gradient38 graphicsObject.FillEllipse(linearBrush, 5, 30, 65, 100)39 40 ' draw thick rectangle outline in red41 graphicsObject.DrawRectangle(thickRedPen, drawArea2)42 43 ' fill textureBitmap with yellow44 solidColorBrush.Color = Color.Yellow45 graphicsObject2.FillRectangle(solidColorBrush, 0, 0, 10, 10)46 47 ' draw small black rectangle in textureBitmap48 coloredPen.Color = Color.Black49 graphicsObject2.DrawRectangle(coloredPen, 1, 1, 6, 6)50 51 ' draw small blue rectangle in textureBitmap52 solidColorBrush.Color = Color.Blue53 graphicsObject2.FillRectangle(solidColorBrush, 1, 1, 3, 3)54 55 ' draw small red square in textureBitmap56 solidColorBrush.Color = Color.Red57 graphicsObject2.FillRectangle(solidColorBrush, 4, 4, 3, 3)58 59 ' create textured brush and display textured rectangle60 Dim texturedBrush As TextureBrush = _61 New TextureBrush(textureBitmap)62 63 graphicsObject.FillRectangle( _64 texturedBrush, 155, 30, 75, 100)65 66 ' draw pie-shaped arc in white67 coloredPen.Color = Color.White68 coloredPen.Width = 669 graphicsObject.DrawPie( _70 coloredPen, 240, 30, 75, 100, 0, 270)

Uses Graphics method FillEllipse to draw an ellipse with brush, the color gradually changes from blue to yellow

Page 49: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline49

DrawShapes.vb

71 72 ' draw lines in green and yellow73 coloredPen.Color = Color.Green74 coloredPen.Width = 575 graphicsObject.DrawLine(coloredPen, 395, 30, 320, 150)76 77 ' draw a rounded, dashed yellow line78 coloredPen.Color = Color.Yellow79 coloredPen.DashCap = LineCap.Round80 coloredPen.DashStyle = DashStyle.Dash81 graphicsObject.DrawLine(coloredPen, 320, 30, 395, 150)82 End Sub ' OnPaint83 84 End Class ' FrmDrawShapes

Page 50: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline50

DrawStars.vb

1 ' Fig. 16.22: DrawStars.vb2 ' Using paths to draw stars on a form.3 4 Imports System.Drawing.Drawing2D5 6 Public Class FrmDrawStars7 Inherits System.Windows.Forms.Form8 9 ' Visual Studio .NET generated code10 11 ' create path and draw stars along it12 Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)13 Dim graphicsObject As Graphics = e.Graphics14 Dim i As Integer15 Dim random As Random = New Random()16 Dim brush As SolidBrush = _17 New SolidBrush(Color.DarkMagenta)18 19 ' x and y points of path20 Dim xPoints As Integer() = _21 {55, 67, 109, 73, 83, 55, 27, 37, 1, 43}22 Dim yPoints As Integer() = _23 {0, 36, 36, 54, 96, 72, 96, 54, 36, 36}24 25 ' create graphics path for star26 Dim star As GraphicsPath = New GraphicsPath()27 28 ' translate origin to (150, 150)29 graphicsObject.TranslateTransform(150, 150)30 31 ' create star from series of points32 For i = 0 To 8 Step 233 star.AddLine(xPoints(i), yPoints(i), _34 xPoints(i + 1), yPoints(i + 1))35 Next

Defines two Integer arrays, representing the x- and y-coordinates of the points in the star

Defines GraphicsPath object star

Sets the origin of the Graphics object

Page 51: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline51

DrawStars.vb

36 37 ' close shape38 star.CloseFigure()39 40 ' rotate origin and draw stars in random colors41 For i = 1 To 1842 graphicsObject.RotateTransform(20)43 44 brush.Color = Color.FromArgb(random.Next(200, 255), _45 random.Next(255), random.Next(255), random.Next(255))46 47 graphicsObject.FillPath(brush, star)48 Next49 50 End Sub ' OnPaint51 52 End Class ' FrmDrawStars

Uses GraphicsPath method CloseFigure to complete the shape

Draws the star 18 times, rotating it around the origin

Uses Graphics method RotateTransform to move to the next position on the form

Graphics method FillPath draws a filled version of the star with the Brush created earlier

Page 52: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

52

16.9 Introduction to Multimedia

• Visual Basic offers many convenient ways to include images and animations in programs

• Computing field decades ago mainly used computers to perform arithmetic calculations– We are beginning to realize the importance of computer’s

data-manipulation capabilities

• Multimedia programming presents many challenges

• Multimedia applications demand extraordinary computing power

Page 53: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

53

16.10 Loading, Displaying and Scrolling Images

• Visual Basic’s multimedia capabilities– Graphics

– Images

– Animations

– Video

• Image manipulation

Page 54: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline54

DisplayLogo.vb

1 ' Fig. 16.23: DisplayLogo.vb2 ' Displaying and resizing an image.3 4 Public Class FrmDisplayLogo5 Inherits System.Windows.Forms.Form6 7 ' width controls8 Friend WithEvents txtWidth As TextBox9 Friend WithEvents lblWidth As Label10 11 ' height controls12 Friend WithEvents lblHeight As Label13 Friend WithEvents txtHeight As TextBox14 15 Private mGraphicsObject As Graphics16 Private mImage As Image17 18 ' sets member variables on form load19 Private Sub FrmDisplayLogo_Load(ByVal sender As _20 System.Object, ByVal e As System.EventArgs) _21 Handles MyBase.Load22 23 ' get Form's graphics object24 mGraphicsObject = Me.CreateGraphics25 26 ' load image27 mImage = Image.FromFile("images/Logo.gif")28 29 End Sub ' FrmDisplayLogo_Load30 31 ' Visual Studio .NET generated code32

Declares Image reference mImage

Uses Form method CreateGraphics to create a Graphics object associated with the Form

The Shared Image method FromFile retrieves an image stored on disk and assigns it to mImage

Page 55: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline55

DisplayLogo.vb

33 Private Sub cmdSetButton_Click (ByVal sender As System.Object, _34 ByVal e As System.EventArgs) Handles cmdSetButton.Click35 36 ' get user input37 Dim width As Integer = Convert.ToInt32(txtWidth.Text)38 Dim height As Integer = Convert.ToInt32(txtHeight.Text)39 40 ' if specified dimensions are too large display problem41 If (width > 375 OrElse height > 225) Then42 MessageBox.Show("Height or Width too large")43 44 Return45 End If46 mGraphicsObject.Clear(Me.BackColor) ' clear Windows Form47 48 ' draw image49 mGraphicsObject.DrawImage(mImage, 5, 5, width, height)50 End Sub ' cmdSetButton_Click51 52 End Class ' FrmDisplayLogo

If the parameters are valid, Graphics method Clear is called to paint the entire Form in the current background color

Graphics method DrawImage is called with the following parameters: the image to draw, the x-coordinate of the upper-left corner, y-

coordinate of the upper-left corner, width of the image, and height of the image

Page 56: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline56

DisplayLogo.vb

Page 57: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

57

16.11 Animating a Series of Images

• Two-dimensional collision detection– Two-dimensional collision detection is the detection of an

overlap between two shapes

• Chess Board– Defined by alternating light and dark tiles across a row in the

pattern where the color that starts each row is equal to the color of last tile of previous row

• Artifacts– An artifact is any unintended visual abnormality in a

graphical program

Page 58: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline58

LogoAnimator.vb

1 ' Fig. 16.24: LogoAnimator.vb2 ' Program that animates a series of images.3 4 Public Class FrmLogoAnimator5 Inherits System.Windows.Forms.Form6 7 Private mImages As ArrayList = New ArrayList()8 Private mCount As Integer = 19 10 Public Sub New()11 MyBase.New()12 13 ' This call is required by Windows Form Designer.14 InitializeComponent()15 16 ' load all images17 Dim i As Integer18 19 For i = 0 To 2920 mImages.Add(Image.FromFile("images/deitel" & i _21 & ".gif"))22 Next23 24 ' load first image25 logoPictureBox.Image = CType(mImages(0), Image)26 27 ' set PictureBox to be same size as Image28 logoPictureBox.Size = logoPictureBox.Image.Size29 End Sub ' New30 31 Friend WithEvents timer As System.Windows.Forms.Timer32 33 Friend WithEvents logoPictureBox As _34 System.Windows.Forms.PictureBox35

Load each of 30 images and place then in an ArrayList

Places the first image in the PictureBox

ArrayList method Add allows is to add objects to the ArrayList

Modifies the size of the PictureBox so that it is equal to the size of the Image it is displaying

Page 59: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline59

LogoAnimator.vb

36 ' Visual Studio .NET generated code37 38 Private Sub timer_Tick(ByVal sender As System.Object, _39 ByVal e As System.EventArgs) Handles timer.tick40 41 ' increment counter42 mCount = (mCount + 1) Mod 3043 44 ' load next image45 logoPictureBox.Image = CType(mImages(mCount), Image)46 End Sub ' Timer_Tick47 48 End Class ' FrmLogoAnimator

The event handler for timer’s Tick event displays the next mage from the ArrayList

Page 60: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline60

Chesspiece.vb

1 ' Fig. 16.25 : Chesspiece.vb2 ' Storage class for chess piece attributes.3 4 Public Class CChessPiece5 6 ' define chess-piece type constants7 Public Enum Types8 KING9 QUEEN10 BISHOP11 KNIGHT12 ROOK13 PAWN14 End Enum15 16 Private mCurrentType As Integer ' this object's type17 Private mPieceImage As Bitmap ' this object's image18 19 ' default display location20 Private mLocationRectangle As Rectangle = _21 New Rectangle(0, 0, 75, 75)22 23 ' construct piece24 Public Sub New(ByVal type As Integer, _25 ByVal xLocation As Integer, ByVal yLocation As Integer, _26 ByVal sourceImage As Bitmap)27 28 mCurrentType = type ' set current type29 mLocationRectangle.X = xLocation ' set current x location30 mLocationRectangle.Y = yLocation ' set current y location31 32 ' obtain pieceImage from section of sourceImage33 mPieceImage = sourceImage.Clone(New Rectangle(type * 75, _34 0, 75, 75), Drawing.Imaging.PixelFormat.DontCare)35 End Sub ' constructor

Define a public enumeration of constants that identify each chess-piece type

Rectangle object mLocationRectangle identifies the image location on the chess board

Extract a subimage that contains only the current piece’s bitmap data

Page 61: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline61

Chesspiece.vb

36 37 ' draw this piece38 Public Sub Draw(ByVal graphicsObect As Graphics)39 graphicsObect.DrawImage(mPieceImage, mLocationRectangle)40 End Sub ' Draw41 42 ' obtain this piece's location rectangle43 Public Readonly Property LocationRectangle As Rectangle44 Get45 Return mLocationRectangle46 End Get47 End Property ' LocationRectangle48 49 ' set this piece's location50 Public Sub SetLocation(ByVal xLocation As Integer, _51 ByVal yLocation As Integer)52 53 mLocationRectangle.X = xLocation54 mLocationRectangle.Y = yLocation55 End Sub ' SetLocation56 57 End Class ' CChesspiece

Method Draw causes the CChessPiece to draw mPieceImage in mLocationRectangle on the passed Graphics object

Page 62: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline62

ChessGame.vb

1 ' Fig. 16.26: ChessGame.vb2 ' Chess Game graphics code.3 4 Imports System.Drawing.Drawing2D5 6 Public Class FrmChessSurface7 Inherits System.Windows.Forms.Form8 9 ' display box10 Friend WithEvents pieceBox As PictureBox11 12 ' game menu13 Friend WithEvents gameMenu As MainMenu14 Friend WithEvents gameItem As MenuItem15 Friend WithEvents newGame As MenuItem16 17 ' Visual Studio .NET generated code18 19 ' ArrayList for board tile images20 Dim mChessTile As ArrayList = New ArrayList()21 22 ' ArrayList for chess pieces23 Dim mChessPieces As ArrayList = New ArrayList()24 25 ' define index for selected piece26 Dim mSelectedIndex As Integer = -127 Dim mBoard As Integer(,) = New Integer(7,7) {} ' board array28 29 ' define chess tile size in pixels30 Private Const TILESIZE As Integer = 7531

Class FrmChessSurface defines the game and graphics code for our chess game

ArrayListmChessTile stores the board tile images

ArrayListmChessPieces stores all active CChessPiece objects

IntegermSelectedIndex identifies the index in mChessPieces of thecurrently selected pieces

Integer TILESIZE is a constant defining the size of each tile in pixels

Page 63: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline63

ChessGame.vb

32 ' load tile bitmaps and reset game33 Private Sub FrmChessSurface_Load(ByVal sender _34 As System.Object, ByVal e As System.EventArgs) _35 Handles MyBase.Load36 37 ' load chess board tiles38 mChessTile.Add(Bitmap.FromFile("lightTile1.png"))39 mChessTile.Add(Bitmap.FromFile("lightTile2.png"))40 mChessTile.Add(Bitmap.FromFile("darkTile1.png"))41 mChessTile.Add(Bitmap.FromFile("darkTile2.png"))42 43 ResetBoard() ' initialize board44 Invalidate() ' refresh form45 End Sub ' FrmChessSurface_Load46 47 ' initialize pieces to start positions and rebuild board48 Private Sub ResetBoard()49 Dim column As Integer = 050 Dim row As Integer = 051 Dim current As Integer52 Dim piece As CChessPiece53 Dim random As Random = New Random()54 Dim light As Boolean = False55 Dim type As Integer56 57 ' ensure empty arraylist58 mChessPieces = New ArrayList()59 60 ' load whitepieces image61 Dim whitePieces As Bitmap = _62 Bitmap.FromFile("whitePieces.png")63 64 ' load blackpieces image65 Dim blackPieces As Bitmap = _66 Bitmap.FromFile("blackPieces.png")

The FrmChessSurface load event loads each tile image into mChessTile

Method ResetBoard assigns mChessPieces to a new ArrayList

Page 64: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline64

ChessGame.vb

67 68 ' set whitepieces drawn first69 Dim selected As Bitmap = whitePieces70 71 ' traverse board rows in outer loop72 For row = 0 To mBoard.GetUpperBound(0)73 74 ' if at bottom rows, set to black piece images75 If row > 5 Then76 selected = blackPieces77 End If78 79 ' traverse board columns in inner loop80 For column = 0 To mBoard.GetUpperBound(1)81 82 ' if first or last row, organize pieces83 If (row = 0 OrElse row = 7) Then84 85 Select Case column86 87 Case 0, 7 ' set current piece to rook88 current = CChessPiece.Types.ROOK89 90 Case 1, 6 ' set current piece to knight91 current = CChessPiece.Types.KNIGHT92 93 Case 2, 5 ' set current piece to bishop94 current = CChessPiece.Types.BISHOP95 96 Case 3 ' set current piece to king97 current = CChessPiece.Types.KING98 99 Case 4 ' set current piece to queen100 current = CChessPiece.Types.QUEEN101 End Select

Loops through 64 positions on the chess board, setting the tile color and piece for each tile

Causes the currently selected image to switch to the blackPieces after the fifth row

Page 65: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline65

ChessGame.vb

102 103 ' create current piece at start position104 piece = New CChessPiece(current, _105 column * TILESIZE, row * TILESIZE, selected)106 107 ' add piece to ArrayList108 mChessPieces.Add(piece)109 End If110 111 ' if second or seventh row, organize pawns112 If (row = 1 OrElse row = 6) Then113 piece = New CChessPiece(CChessPiece.Types.PAWN, _114 column * TILESIZE, row * TILESIZE, selected)115 116 mChessPieces.Add(piece)117 End If118 119 ' determine board piece type120 type = random.Next(0, 2)121 122 If light Then ' set light tile123 mBoard(row, column) = type124 light = False125 Else ' set dark tile126 mBoard(row, column) = type + 2127 light = True128 End If129 130 Next ' next column131 132 ' account for new row tile color switch133 light = Not light134 Next ' next row135 136 End Sub ' ResetBoard

Add a new pawn at the current location if the current row is second or seventh

Assigns the current board-tile color as an index in the mBoard array

Page 66: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline66

ChessGame.vb

137 138 ' display board in form OnPaint event139 Protected Overrides Sub OnPaint(ByVal paintEvent _140 As PaintEventArgs)141 142 ' obtain graphics object143 Dim graphicsObject As Graphics = paintEvent.Graphics144 Dim row, column As Integer145 146 For row = 0 To mBoard.GetUpperBound(0)147 148 For column = 0 To mBoard.GetUpperBound(1)149 150 ' draw image specified in board array151 graphicsObject.DrawImage( _152 CType(mChessTile(mBoard(row, column)), _153 Image), New Point(TILESIZE * column, _ 154 TILESIZE * row))155 Next156 157 Next158 159 End Sub ' OnPaint160 161 ' return index of piece that intersects point162 ' optionally exclude a value163 Private Function CheckBounds(ByVal point As Point, _164 Optional ByVal exclude As Integer = -1) As Integer165 166 Dim rectangle As Rectangle ' current bounding rectangle167 Dim i As Integer168

Method OnPaint overrides class Form’s OnPaint method and draws the tiles according to their values in the board array

Method CheckBounds is a collision-detection helper method

Page 67: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline67

ChessGame.vb

169 For i = 0 To mChessPieces.Count - 1170 171 ' get piece rectangle172 rectangle = Getpiece(i).LocationRectangle()173 174 ' check if rectangle contains point175 If (rectangle.Contains(point) AndAlso i <> exclude) Then176 Return i177 End If178 179 Next180 181 Return -1182 End Function ' CheckBounds183 184 ' handle pieceBox pain event185 Private Sub pieceBox_Paint(ByVal sender As System.Object, _186 ByVal e As System.Windows.Forms.PaintEventArgs) _187 Handles pieceBox.Paint188 189 Dim i As Integer190 191 ' draw all pieces192 For i = 0 To mChessPieces.Count - 1193 Getpiece(i).Draw(e.Graphics)194 Next195 196 End Sub ' pieceBox_Paint197

Page 68: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline68

ChessGame.vb

198 ' on MouseDown event, select chess piece199 Private Sub pieceBox_MouseDown(ByVal sender As System.Object, _200 ByVal e As System.Windows.Forms.MouseEventArgs) _201 Handles pieceBox.MouseDown202 203 ' determine selected piece204 mSelectedIndex = CheckBounds(New Point(e.X, e.Y))205 End Sub ' pieceBox_MouseDown206 207 ' if piece is selected, move it208 Private Sub pieceBox_MouseMove(ByVal sender As System.Object, _209 ByVal e As System.Windows.Forms.MouseEventArgs) _210 Handles pieceBox.MouseMove211 212 If mSelectedIndex > -1 Then213 214 Dim region As Rectangle = New Rectangle(e.X - _215 TILESIZE * 2, e.Y - TILESIZE * 2, TILESIZE * 4, _ 216 TILESIZE * 4)217 218 ' set piece center to mouse219 Getpiece(mSelectedIndex).SetLocation(e.X - _220 TILESIZE / 2, e.Y - TILESIZE / 2)221 222 ' refresh immediate area223 pieceBox.Invalidate(region)224 End If225 226 End Sub ' pieceBox_MouseMove227

The MouseDown event handler calls method CheckBounds with the location of the user’s click to determine whether the user selected a piece

The MouseMove event handler moves the currently selected piece with the mouse

Define a refresh a region of the Panel thatspans two tiles in every from the mouse

Page 69: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline69

ChessGame.vb

228 ' on mouse up, deselect chess piece and remove taken piece229 Private Sub pieceBox_MouseUp(ByVal sender As _230 System.Object, ByVal e As _231 System.Windows.Forms.MouseEventArgs) _232 Handles pieceBox.MouseUp233 234 Dim remove As Integer = -1235 236 If mSelectedIndex > -1 Then ' if chess piece was selected237 238 Dim current As Point = New Point(e.X, e.Y)239 Dim newPoint As Point = New Point(current.X - _240 current.X Mod TILESIZE, current.Y - _241 current.Y Mod TILESIZE)242 243 ' check bounds with point, exclude selected piece244 remove = CheckBounds(current, mSelectedIndex)245 246 ' snap piece into center of closest square247 Getpiece(mSelectedIndex).SetLocation(newPoint.X, _248 newPoint.Y)249 250 mSelectedIndex = -1 ' deselect piece251 252 ' remove taken piece253 If remove > -1 Then254 mChessPieces.RemoveAt(remove)255 End If256 257 End If258 259 ' refresh pieceBox to ensure artifact removal260 pieceBox.Invalidate()261 End Sub ' pieceBox_MouseUp262

Define the MouseUp event handler

Checks whether any piece is beneath the current mouse location

Determine the closest valid chess tile and “snap” the selected piece to that location

Panel is Invalidated in order to display the new piece location and remove any artifacts created during the move

Page 70: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline70

ChessGame.vb

263 ' helper function to convert ArrayList object as CChesspiece264 Private Function Getpiece(ByVal i As Integer) _265 As CChessPiece266 267 Return CType(mChessPieces(i), CChessPiece)268 End Function ' Getpiece269 270 ' handle NewGame menu option click271 Private Sub NewGame_Click(ByVal sender As Object, _272 ByVal e As System.EventArgs) Handles NewGame.Click273 274 ResetBoard() ' re-initialize board275 Invalidate() ' refresh form276 End Sub ' NewGame_Click277 278 End Class ' FrmChessSurface

Define helper function GetPiece that simplifies the conversion from Objects in the ArrayListmChessPieces to CChessPiece types

Page 71: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline71

ChessGame.vb

Page 72: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline72

ChessGame.vb

Page 73: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline73

ChessGame.vb

Page 74: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

74

16.12 Windows Media Player

• Windows Media player – Enables an application to play video and sound in many

multimedia formats• Motion Pictures Experts Group (MPEG)

• Audio-Video Interleave (AVI)

• Windows wave-file format (WAV)

• Musical Instrument Digital Interface (MIDI)

Page 75: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline75

MediaPlayerTest.vb

1 ' Fig 16.27: MediaPlayerTest.vb2 ' Demonstrates the Windows Media Player control3 4 Public Class FrmMediaPlayer5 Inherits System.Windows.Forms.Form6 7 ' action menus8 Friend WithEvents applicationMenu As MainMenu9 Friend WithEvents fileItem As MenuItem10 Friend WithEvents openItem As MenuItem11 Friend WithEvents exitItem As MenuItem12 Friend WithEvents aboutItem As MenuItem13 Friend WithEvents aboutMessageItem As MenuItem14 15 ' media player control16 Friend WithEvents player As AxMediaPlayer.AxMediaPlayer17 Friend WithEvents openMediaFileDialog As OpenFileDialog18 19 ' Visual Studio .NET generated code20 21 ' open new media file in Windows Media Player22 Private Sub openItem_Click(ByVal sender As System.Object, _23 ByVal e As System.EventArgs) Handles openItem.Click24 25 openMediaFileDialog.ShowDialog()26 27 player.FileName = openMediaFileDialog.FileName28 29 ' adjust the size of the Media Player control and the30 ' Form according to the size of the image31 player.Size = New Size( _32 player.ImageSourceWidth, player.ImageSourceHeight)33 34 Me.Size = New Size(player.Size.Width + 20, _35 player.Size.Height + 60)36 End Sub ' openItem_Click

Adjust the size of the player and the application to reflect the size of the media contained in the file

Page 76: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline76

MediaPlayerTest.vb

37 38 ' exit application39 Private Sub exitItem_Click(ByVal sender As System.Object, _40 ByVal e As System.EventArgs) Handles exitItem.Click41 42 Application.Exit()43 End Sub ' exitItem_Click44 45 ' show the About box for Windows Media Player46 Private Sub aboutMessageItem_Click(ByVal sender As _47 System.Object, ByVal e As System.EventArgs) _48 Handles aboutMessageItem.Click49 50 player.AboutBox()51 End Sub ' aboutMessageItem_Click52 53 End Class ' FrmMediaPlayer

The event handler that executes when the user chooses About Windows Media Player from the About menu calls the AboutBox method of the player

Page 77: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline77

MediaPlayerTest.vb

Page 78: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline78

MediaPlayerTest.vb

Page 79: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

79

16.13 Microsoft Agent

• Microsoft Agent– Microsoft Agent is a technology used to add interactive

animated characters to Windows applications or Web pages• Microsoft Agent control provides programmers with access to

four predefined characters: Genie (a genie), Merlin (a wizard), Peedy (a parrot), and Robby (a robot)

– Microsoft Agent technology enables users to interact with applications Web pages through speech

• When the user speaks into a microphone the control uses a speech recognition engine that translates vocal sound into a language that computer understands

• A text speech engine is an application that translates typed words into audio sound that users hear through headphones or speakers connected to a computer

Page 80: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

80

16.13 Microsoft Agent

Fig. 16.28 Peedy introducing himself when the window opens.

Page 81: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

81

16.13 Microsoft Agent

Fig. 16.29 Peedy’s Pleased animation.

Page 82: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

82

16.13 Microsoft Agent

Fig. 16.30 Peedy’s reaction when he is clicked.

Page 83: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

83

16.13 Microsoft Agent

Fig. 16.31 Peedy flying animation

Page 84: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

84

16.13 Microsoft Agent

Fig. 16.32 Peedy waiting for speech input.

Page 85: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

85

16.13 Microsoft Agent

Fig. 16.33 Peedy repeating the user’s request for Seattle style pizza.

Page 86: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

86

16.13 Microsoft Agent

Fig. 16.34 Peedy repeating the user’s request for anchovies as an additional topping.

Page 87: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

87

16.13 Microsoft Agent

Fig. 16.35 Peedy recounting the order.

Page 88: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall. All rights reserved.

88

16.13 Microsoft Agent

Fig. 16.36 Peedy calculating the total.

Page 89: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline89

Agent.vb

1 ' Fig. 16.37: Agent.vb2 ' Demonstrating Microsoft Agent.3 4 Imports System.IO5 Imports System.Collections6 Imports System.Windows.Forms7 8 Public Class FrmAgent9 Inherits System.Windows.Forms.Form10 11 ' options12 Friend WithEvents characterCombo As ComboBox13 Friend WithEvents actionsCombo As ComboBox14 15 Friend WithEvents GroupBox1 As GroupBox16 Friend WithEvents cmdSpeak As Button17 Friend WithEvents mainAgent As AxAgentObjects.AxAgent18 19 ' input boxes20 Friend WithEvents txtLocation As TextBox21 Friend WithEvents txtSpeech As TextBox22 23 ' current agent object24 Private mSpeaker As AgentObjects.IAgentCtlCharacter25 26 ' Visual Studio .NET generated code27 28 ' keyDown event handler for locationTextBox29 Private Sub txtLocation_KeyDown(ByVal sender As _30 Object, ByVal e As System.Windows.Forms.KeyEventArgs)_31 Handles txtLocation.KeyDown32 33 If e.KeyCode = Keys.Enter Then34

Create an object named mSpeaker

Page 90: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline90

Agent.vb

35 ' set character location to text box value36 Dim location As String = txtLocation.Text37 38 ' initialize characters39 Try40 41 ' load characters into agent object42 mainAgent.Characters.Load( _43 "Genie", location & "Genie.acs")44 45 mainAgent.Characters.Load( _46 "Merlin", location & "Merlin.acs")47 48 mainAgent.Characters.Load( _49 "Peedy", location & "Peedy.acs")50 51 mainAgent.Characters.Load( _52 "Robby", location & "Robby.acs")53 54 ' disable TextBox location and enable other controls55 txtLocation.Enabled = False56 txtSpeech.Enabled = True57 cmdSpeak.Enabled = True58 characterCombo.Enabled = True59 actionsCombo.Enabled = True60 61 ' set current character to Genie and show62 mSpeaker = mainAgent.Characters("Genie")63 GetAnimationNames() ' obtain animation name list64 mSpeaker.Show(0)65 66 Catch fileNotFound As FileNotFoundException67 MessageBox.Show("Invalid character location", _68 "Error", MessageBoxButtons.OK, _69 MessageBoxIcon.Error)70 End Try

Disable txtLocation and enable the rest of the controls

Set Genie as a default character

Page 91: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline91

Agent.vb

71 72 End If73 74 End Sub ' txtLocation_KeyDown75 76 ' speak button event handler77 Private Sub cmdSpeak_Click(ByVal sender As System.Object, _78 ByVal e As System.EventArgs) Handles cmdSpeak.Click79 80 ' if TextBox is empty, have character ask81 ' user to type words into TextBox, otherwise82 ' have character say words in TextBox83 If txtSpeech.Text = "" Then84 mSpeaker.Speak( _85 "Please type the words you want me to speak", "")86 Else87 mSpeaker.Speak(txtSpeech.Text, "")88 End If89 90 End Sub ' cmdSpeak_Click91 92 ' click event for agent93 Private Sub mainAgent_ClickEvent(ByVal sender As Object _94 Object, ByVal e As AxAgentObjects._AgentEvents_ClickEvent)_95 Handles mainAgent.ClickEvent96 97 mSpeaker.Play("Confused")98 mSpeaker.Speak("Why are you poking me?", "")99 mSpeaker.Play("RestPose")100 End Sub ' mainAgent_ClickEvent101

When the user clicks the character, event handler mainAgent_ClickEvent executes

First, mSpeaker method Play plays animation

Page 92: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline92

Agent.vb

102 ' comboBox changed event, switch active agent103 Private Sub characterCombo_SelectedIndexChanged(ByVal _104 sender As System.Object, ByVal e As System.EventArgs) _105 Handles characterCombo.SelectedIndexChanged106 107 ChangeCharacter(characterCombo.Text)108 End Sub ' characterCombo_SelectedIndexChanged109 110 ' hide current character and show new111 Private Sub ChangeCharacter(ByVal name As String)112 mSpeaker.Hide(0)113 mSpeaker = mainAgent.Characters(name)114 GetAnimationNames() ' regenerate animation name list115 mSpeaker.Show(0)116 End Sub ' ChangeCharacter117 118 ' get animation names and store in arraylist119 Private Sub GetAnimationNames()120 121 ' ensure thread safety122 SyncLock (Me)123 124 ' get animation names125 Dim enumerator As IEnumerator = _126 mainAgent.Characters.Character( _127 mSpeaker.Name).AnimationNames.GetEnumerator()128 129 Dim voiceString As String130 131 ' clear cboActions combo box132 actionsCombo.Items.Clear()133 mSpeaker.Commands.RemoveAll()134

Method GetAnimationNames fills the actionsCombo ComboBox with the current character’s animation listing and defines the valid commands

Assigns the newly selected character to mSpeaker

Generates the character’s animation names and commands

Method Show displays the character

Page 93: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline93

Agent.vb

135 ' copy enumeration to ArrayList136 While enumerator.MoveNext() 137 138 ' remove underscores in speech string139 voiceString = Convert.ToString(enumerator.Current)140 voiceString = voiceString.Replace("_", "underscore")141 142 actionsCombo.Items.Add(enumerator.Current)143 144 ' add all animations as voice enabled commands145 mSpeaker.Commands.Add(Convert.ToString( _146 enumerator.Current, , voiceString, True, False)147 End While148 149 ' add custom command150 mSpeaker.Commands.Add("MoveToMouse", "MoveToMouse", _151 "MoveToMouse", True, True)152 End SyncLock153 154 End Sub ' GetAnimationNames155 156 ' user selects new action157 Private Sub actionsCombo_SelectedIndexChanged(ByVal sender _158 As System.Object, ByVal e As System.EventArgs) _159 Handles actionsCombo.SelectedIndexChanged160 161 mSpeaker.Stop()162 mSpeaker.Play(actionsCombo.Text)163 mSpeaker.Play("RestPose")164 End Sub ' actionsCombo_SelectedIndexChanged165

Iterate through all items in the animation name enumerator

Removes any underscore characters and replaces them with String “underscore”

The Add method of the Commands property adds a new command to the current character

Creates a new command named MoveToMouse that is visible in the Commands pop-up window

Page 94: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline94

Agent.vb

166 ' handles agent commands167 Private Sub mainAgent_Command(ByVal sender As System.Object, _168 ByVal e As AxAgentObjects._AgentEvents_CommandEvent) _169 Handles mainAgent.Command170 171 ' get UserInput object172 Dim command As AgentObjects.IAgentCtlUserInput = _173 CType(e.userInput, AgentObjects.IAgentCtlUserInput)174 175 ' change character if user speaks character name176 If (command.Voice = "Peedy" OrElse _177 command.Voice = "Robby" OrElse _178 command.Voice = "Merlin" OrElse _179 command.Voice = "Genie") Then180 ChangeCharacter(command.Voice)181 182 Return183 End If184 185 ' send agent to mouse186 If command.Name = "MoveToMouse" Then187 mSpeaker.MoveTo(Convert.ToInt16( _188 Cursor.Position.X - 60), Convert.ToInt16( _189 Cursor.Position.Y - 60))190 191 Return192 End If193 194 ' play new animation195 mSpeaker.Stop()196 mSpeaker.Play(command.Name)197 198 End Sub ' mainAgent_Command199 200 End Class ' FrmAgent

Uses method ChangeCharacter to change the current Agent character if the user speaks a character name

Moves the character to the current mouse location if the user invokes the MoveToMouse command

Page 95: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline95

Agent.vb

Page 96: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline96

Agent.vb

Page 97: Chapter 16 – Graphics and Multimedia

2002 Prentice Hall.All rights reserved.

Outline97

Agent.vb