You are on page 1of 49

Visual Basic 2005

VII. GRAPHICS AND MULTIMEDIA

MELJUN CORTES

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 Visual Basic application. To use Microsoft Agent to add interactive animated characters to a Visual Basic application.

Graphics and Multimedia


Objectives
GRAPHICS AND MULTIMEDIA 2

Visual Basic 2005

Graphics and Multimedia

The FCL supports graphics that enable programmers to visually enhance their Windows applications The many sophisticated drawing capabilities are part of namespace System.Drawing and the other namespaces that make up the .NET resource GDI+ GDI+ is an application programming interface (API) that provides classes for creating two-dimensional vector graphics, manipulating fonts and inserting images

Overview
GRAPHICS AND MULTIMEDIA 3

Visual Basic 2005

Graphics and Multimedia

Namespaces System.Drawing and System.Drawing.Drawing2D contain the most commonly used GDI+ components
System.Object System.MarshalByRefObject Font FontFamily Graphics Icon Pen Region SolidBrush Brush HatchBrush LinearGradientBrush PathGradientBrush SolidBrush TextureBrush Color Point Rectangle Size

Drawing Classes and the Coordinate System


GRAPHICS AND MULTIMEDIA 4

Visual Basic 2005

Graphics and Multimedia

Class Graphics contains methods used for drawing Strings, lines, rectangles and other shapes on a Control The drawing methods of class Graphics usually require a Pen or Brush object to render a specified shape The Pen draws shape outlines; the Brush draws solid objects

Drawing Classes and the Coordinate System


GRAPHICS AND MULTIMEDIA 5

Visual Basic 2005

Graphics and Multimedia

The Color structure contains numerous Shared properties that set the colors of various graphical components, plus methods that allow users to create new colors Class Font contains properties that define unique fonts Class FontFamily contains methods for obtaining font information

Drawing Classes and the Coordinate System


GRAPHICS AND MULTIMEDIA 6

Visual Basic 2005

Graphics and Multimedia

To begin drawing in Visual Basic, we first must understand GDI+'s coordinate system, a scheme for identifying every point on the screen
(0, 0) +x X Axis

+y

(x, y)

Y Axis

Drawing Classes and the Coordinate System


GRAPHICS AND MULTIMEDIA 7

Visual Basic 2005

Graphics and Multimedia

A graphics context represents a drawing surface that enables drawing on the screen A Graphics object manages a graphics context by controlling how information is drawn Graphics objects contain methods for drawing, font manipulation, color manipulation and other graphics-related actions

Graphics Context and Graphics Objects


GRAPHICS AND MULTIMEDIA 8

Visual Basic 2005

Graphics and Multimedia

When drawing on a Form, you can override method OnPaint to retrieve a Graphics object from argument PaintEventArgs or to create a new Graphics object associated with the appropriate surface To override the inherited OnPaint method, use the following method header:
Protected Overrides Sub OnPaint(PaintEventArgs e)

Next, extract the incoming Graphics object from argument PaintEventArg, as in:
Dim graphicsObject As Graphics = e.Graphics

Graphics Context and Graphics Objects


GRAPHICS AND MULTIMEDIA 9

Visual Basic 2005

Graphics and Multimedia

Variable graphicsObject can now be used to draw shapes and Strings on the Form Instead of overriding the OnPaint method, programmers can add an event handler for the Paint event Visual Studio .NET generates the Paint event handler in this form:

Protected Sub MyEventHandler_Paint( _ ByVal sender As Object, ByVal e As PaintEventArgs)

Graphics Context and Graphics Objects


GRAPHICS AND MULTIMEDIA 10

Visual Basic 2005

Graphics and Multimedia

Controls, such as Labels and Buttons, do not have their own graphics contexts, but you can create them To draw on a control, first create a graphics object by invoking the control's CreateGraphics method, as in:

Dim graphicsObject As Graphics = controlName.CreateGraphics()

Graphics Context and Graphics Objects


GRAPHICS AND MULTIMEDIA 11

Visual Basic 2005

Graphics and Multimedia

Colors can enhance a program's appearance and help convey meaning Structure Color defines methods and constants used to manipulate colors Every color can be created from a combination of alpha, red, green and blue components (called ARGB values) All four ARGB components are Bytes that represent integer values in the range 0 to 255 The alpha value determines the opacity of the color

Color Control
GRAPHICS AND MULTIMEDIA 12

Visual Basic 2005

Graphics and Multimedia

Color structure Shared constants and their RGB values:


Constants in structure Color Orange Pink Cyan Magenta RGB Value Constants in structure color White Gray DarkGray Red RGB Value

255, 200, 0 255, 175, 175 0, 255, 255 255, 0, 255

255, 255, 255 128, 128, 128 64, 64, 64 255, 0, 0

Yellow
Black

255, 255, 0
0, 0, 0

Green
Blue

0, 255, 0
0, 0, 255

Color Control
GRAPHICS AND MULTIMEDIA 13

Visual Basic 2005

Graphics and Multimedia

Color structure members:


Structure Color methods and properties Common Methods FromArgb A Shared 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. A Shared method that creates a color from a name, passed as a String. A byte between 0 and 255, representing the alpha component. A byte between 0 and 255, representing the red component. A byte between 0 and 255, representing the green component. A byte between 0 and 255, representing the blue component. Description

FromName Common Properties A R G B

Color Control
GRAPHICS AND MULTIMEDIA 14

Visual Basic 2005

Graphics and Multimedia

Manipulating colors
Public Class FrmShowColors ' color for back rectangle Private backgroundColor As Color = Color.Wheat ' color for front rectangle Private foregroundColor As Color = Color.FromArgb(100, 0, 0, 255)

' override Form's OnPaint method Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) Dim graphicsObject As Graphics = e.Graphics ' get graphics object
' create text brush Dim textBrush As New SolidBrush(Color.Black) ' create solid brush Dim brush As New SolidBrush(Color.White) ' draw white background graphicsObject.FillRectangle(brush, 4, 4, 270, 180) ' display name of backColor graphicsObject.DrawString(BackColor.Name, Me.Font, textBrush, 40, 5) . . .continued

Color Control
GRAPHICS AND MULTIMEDIA 15

Visual Basic 2005

Graphics and Multimedia

Manipulating colors
' set brush color and display back rectangle brush.Color = backgroundColor graphicsObject.FillRectangle(brush, 45, 20, 150, 120) ' display Argb values of front color graphicsObject.DrawString("Alpha: " & foregroundColor.A & _ " Red: " & foregroundColor.R & " Green: " & _ foregroundColor.G & " Blue: " & foregroundColor.B, Me.Font, textBrush, 55, 165) ' set brush color and display front rectangle brush.Color = foregroundColor graphicsObject.FillRectangle(brush, 65, 35, 170, 130) End Sub ' OnPaint ' change Form's background color Private Sub btnColorName_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnColorName.Click ' set backColor to color specified in text box backgroundColor = Color.FromName(txtColorName.Text) Invalidate() ' refresh Form End Sub ' btnColorName_Click . . .continued

Color Control
GRAPHICS AND MULTIMEDIA 16

Visual Basic 2005

Graphics and Multimedia

Manipulating colors
change Form's foreground color Private Sub btnColorValue_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnColorValue.Click ' obtain new front color from text boxes foregroundColor = Color.FromArgb(Convert.ToInt32(txtAlpha.Text), _ Convert.ToInt32(txtRed.Text), _ Convert.ToInt32(txtGreen.Text), _ Convert.ToInt32(txtBlue.Text)) Invalidate() ' refresh Form End Sub ' btnColorValue_Click End Class

Color Control
GRAPHICS AND MULTIMEDIA 17

Visual Basic 2005

Graphics and Multimedia

Manipulating colors

Color Control
GRAPHICS AND MULTIMEDIA 18

Visual Basic 2005

Graphics and Multimedia

The properties of Font objects cannot be modified If you need a different Font, you must create a new Font object There are many overloaded versions of the Font constructor for initializing Font objects

Font Control
GRAPHICS AND MULTIMEDIA 19

Visual Basic 2005

Font class read-only properties

Graphics and Multimedia

Font class read-only properties


Property Bold FontFamily Height Italic Name Size Description Returns true if the font is bold. Returns the font's FontFamily a grouping structure to organize fonts and define their similar properties. Returns the height of the font. Returns true if the font is italic. Returns the font's name as a String. Returns a float value indicating the current font size measured in design units (design units are any specified unit of measurement for the font). Returns a float value indicating the current font size measured in points. Returns True if the font is in strikeout format. Returns true if the font is underlined.

SizeInPoints Strikeout Underline

Font Control
GRAPHICS AND MULTIMEDIA 20

Visual Basic 2005

Graphics and Multimedia

Fonts and FontStyles


Public Class FrmUsingFonts ' demonstrate various font and style settings Protected Overrides Sub OnPaint(ByVal paintEvent As PaintEventArgs) Dim graphicsObject As Graphics = paintEvent.Graphics Dim brush As New SolidBrush(Color.DarkBlue) ' arial, 12 pt bold Dim style As FontStyle = FontStyle.Bold Dim arial As New Font("Arial", 12, style) ' times new roman, 12 pt regular style = FontStyle.Regular Dim timesNewRoman As New Font("Times New Roman", 12, style) ' courier new, 16 pt bold and italic style = FontStyle.Bold Or FontStyle.Italic Dim courierNew As New Font("Courier New", 16, style) . . .continued

Font Control
GRAPHICS AND MULTIMEDIA 21

Visual Basic 2005

Graphics and Multimedia

Fonts and FontStyles


' tahoma, 18 pt strikeout style = FontStyle.Strikeout Dim tahoma As New Font("Tahoma", 18, style) graphicsObject.DrawString(arial.Name & _ " 12 point bold.", arial, brush, 10, 10) graphicsObject.DrawString(timesNewRoman.Name & _ " 12 point plain.", timesNewRoman, brush, 10, 30) graphicsObject.DrawString(courierNew.Name & _ " 16 point bold and italic.", courierNew, brush, 10, 50) graphicsObject.DrawString(tahoma.Name & _ " 18 point strikeout.", tahoma, brush, 10, 70) End Sub ' OnPaint End Class

Font Control
GRAPHICS AND MULTIMEDIA 22

Visual Basic 2005

Graphics and Multimedia

Fonts and FontStyles

Font Control
GRAPHICS AND MULTIMEDIA 23

Visual Basic 2005

Graphics and Multimedia

You can determine precise information about a font's metrics (or properties), such as height, descent, ascent and leading

Font Control
GRAPHICS AND MULTIMEDIA 24

Visual Basic 2005

Graphics and Multimedia

FontFamily methods that return fontmetric information


Method GetCellAscent GetCellDescent GetEmHeight GetLineSpacing Description Returns an Integer representing the ascent of a font as measured in design units. Returns an Integer representing the descent of a font as measured in design units. Returns an Integer representing the height of a font as measured in design units. Returns an Integer representing the distance between two consecutive lines of text as measured in design units.

Font Control
GRAPHICS AND MULTIMEDIA 25

Visual Basic 2005

Graphics and Multimedia

Each of the drawing methods has several overloaded versions Methods that draw hollow shapes typically require as arguments a Pen and four Integers Methods that draw solid shapes typically require as arguments a Brush and four Integers

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 26

Visual Basic 2005

Graphics and Multimedia

Draws a line from (x1, y1) to (x2, y2). The Pen determines the line's color, style and width:
DrawLine(ByVal p As Pen, ByVal x1 As Integer, ByVal y1 As Integer, _ ByVal x2 As Integer, ByVal y2 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 rectangle's color, style and border width
DrawRectangle(ByVal p As Pen, ByVal x As Integer, _ ByVal y As Integer, ByVal width As Integer, _ ByVal height As Integer)

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 27

Visual Basic 2005

Graphics and Multimedia

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.
FillRectangle(ByVal b As Brush, ByVal x As Integer, _ ByVal y As Integer, ByVal width As Integer, _ ByVal height As Integer)

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.
DrawEllipse(ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, _ ByVal width As Integer, ByVal height As Integer)

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 28

Visual Basic 2005

Graphics and Multimedia

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.
FillEllipse(ByVal b As Brush, ByVal x As Integer, _ ByVal y As Integer, ByVal width As Integer, _ ByVal height As Integer)

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 29

Visual Basic 2005

Graphics and Multimedia

Demonstration of methods that draw lines, rectangles and ellipses


Public Class FrmLinesRectanglesOvals ' override Form OnPaint method Protected Overrides Sub OnPaint(ByVal paintEvent As PaintEventArgs) ' get graphics object Dim g As Graphics = paintEvent.Graphics Dim brush As New SolidBrush(Color.Blue) Dim pen As New Pen(Color.Black) ' create filled rectangle g.FillRectangle(brush, 90, 30, 150, 90) ' draw lines to g.DrawLine(pen, g.DrawLine(pen, g.DrawLine(pen, g.DrawLine(pen, connect rectangles 90, 30, 110, 40) 90, 120, 110, 130) 240, 30, 260, 40) 240, 120, 260, 130)

' draw top rectangle g.DrawRectangle(pen, 110, 40, 150, 90) . . .continued

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 30

Visual Basic 2005

Graphics and Multimedia

Demonstration of methods that draw lines, rectangles and ellipses


' set brush to red brush.Color = Color.Red ' draw base Ellipse g.FillEllipse(brush, 280, 75, 100, 50) ' draw connecting lines g.DrawLine(pen, 380, 55, 380, 100) g.DrawLine(pen, 280, 55, 280, 100) ' draw Ellipse outline g.DrawEllipse(pen, 280, 30, 100, 50) End Sub ' OnPaint End Class

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 31

Visual Basic 2005

Graphics and Multimedia

Demonstration of methods that draw lines, rectangles and ellipses

Drawing Lines, Rectangles and Ovals


GRAPHICS AND MULTIMEDIA 32

Visual Basic 2005

Graphics and Multimedia

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

Drawing Arcs
GRAPHICS AND MULTIMEDIA 33

Visual Basic 2005

Graphics and Multimedia

Positive and negative arc angles

Drawing Arcs
GRAPHICS AND MULTIMEDIA 34

Visual Basic 2005

Graphics and Multimedia

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
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)

Drawing Arcs
GRAPHICS AND MULTIMEDIA 35

Visual Basic 2005

Graphics and Multimedia

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 upperleft 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)

Drawing Arcs
GRAPHICS AND MULTIMEDIA 36

Visual Basic 2005

Graphics and Multimedia

Functions similarly to DrawPie, except draws a solid arc (i.e., a sector). The Brush determines the fill pattern for the solid 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)

Drawing Arcs
GRAPHICS AND MULTIMEDIA 37

Visual Basic 2005

Graphics and Multimedia

Polygons are multisided shapes There are several Graphics methods used to draw polygons

Method DrawLines Description Draws a series of connected lines. The coordinates of each point are specified in an array of Point objects. If the last point is different from the first point, the figure is not closed. 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. 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.

DrawPolygon

FillPolygon

Drawing Polygons and Polylines


GRAPHICS AND MULTIMEDIA 38

Visual Basic 2005

Graphics and Multimedia

The FCL offers many other graphics capabilities The Brush hierarchy, for example, also includes HatchBrush, LinearGradientBrush, PathGradientBrush and TextureBrush

Advanced Graphics Capabilities


GRAPHICS AND MULTIMEDIA 39

Visual Basic 2005

Graphics and Multimedia

Shapes drawn on a form

Advanced Graphics Capabilities


GRAPHICS AND MULTIMEDIA 40

Visual Basic 2005

Graphics and Multimedia

A general path is a shape constructed from straight lines and complex curves An object of class GraphicsPath (namespace System.Drawing.Drawing2D) represents a general path The GraphicsPath class provides functionality that enables the creation of complex shapes from vector-based primitive graphics objects

Advanced Graphics Capabilities


GRAPHICS AND MULTIMEDIA 41

Visual Basic 2005

Graphics and Multimedia

Paths used to draw stars on a form

Advanced Graphics Capabilities


GRAPHICS AND MULTIMEDIA 42

Visual Basic 2005

Graphics and Multimedia

The FCL offers many convenient ways to include images and animations in programs Multimedia programming is an entertaining and innovative field, but one that presents many challenges Multimedia applications demand extraordinary computing power

Introduction to Multimedia
GRAPHICS AND MULTIMEDIA 43

Visual Basic 2005

Graphics and Multimedia

Visual Basic's multimedia capabilities include graphics, images, animations and video

Application that loads and displays an image based on the width and height set by the user

Loading, Displaying and Scaling Images


GRAPHICS AND MULTIMEDIA 44

Visual Basic 2005

Graphics and Multimedia

The Windows Media Player control enables an application to play video and sound in many multimedia formats These include:

MPEG (Motion Pictures Experts Group) audio and video AVI (audio-video interleave) video WAV (Windows wave-file format) audio MIDI (Musical Instrument Digital Interface) audio

Windows Media Player


GRAPHICS AND MULTIMEDIA 45

Visual Basic 2005

Graphics and Multimedia

Windows Media Player demonstration


Public Class FrmMediaPlayer ' open new media file in Windows Media Player Private Sub openItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles openItem.Click openMediaFileDialog.ShowDialog() ' load and play the media clip player.URL = openMediaFileDialog.FileName End Sub ' openItem_Click ' exit program when exit menu item is clicked Private Sub exitItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles exitItem.Click Application.Exit() End Sub ' exitItem_Click End Class

Windows Media Player


GRAPHICS AND MULTIMEDIA 46

Visual Basic 2005

Graphics and Multimedia

Windows Media Player demonstration

Windows Media Player control

Video file loaded into the Windows Media Player

Windows Media Player


GRAPHICS AND MULTIMEDIA 47

Visual Basic 2005

Graphics and Multimedia

Exercise
GRAPHICS AND MULTIMEDIA 48

Visual Basic 2005

End of Graphics and Multimedia


GRAPHICS AND MULTIMEDIA 49

Visual Basic 2005