Presentation is loading. Please wait.

Presentation is loading. Please wait.

McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 13 Graphics, Animation, Sound and Drag-and-Drop.

Similar presentations


Presentation on theme: "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 13 Graphics, Animation, Sound and Drag-and-Drop."— Presentation transcript:

1 McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 13 Graphics, Animation, Sound and Drag-and-Drop

2 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-2 Chapter Objectives - 1 Use Graphics methods to draw shapes, lines, and filled shapes Draw on a drawing surface of a Graphics object using Pen and Brush objects Create animation by changing pictures at run time Create simple animation by moving images Automate animation using a Timer component

3 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-3 Chapter Objectives - 2 Move an image using scroll bars Play sounds in an application using a SoundPlayer object Play videos on a form Incorporate drag-and-drop events into your program Draw a pie chart using the methods of the Graphics object

4 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-4 Graphics in Windows and the Web Graphics refers to any text, drawing, image, or icon that is displayed on the screen in either: –Windows Forms PictureBox control –Accepts more file formats than Web forms Graphics shapes are circles, lines, and rectangles on a form or control –Web Forms Image control

5 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-5 The Graphics Environment.NET framework uses GDI+ technology for drawing graphics –GDI+ is designed to be device-independent –Code to draw a graphic is the same regardless of the output device

6 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-6 Steps for Drawing Graphics Create a Graphics object to use as a drawing surface Instantiate a Pen or Brush object to draw with Call the drawing methods of the Graphics object This procedure is the same as the DrawString method used to place text on the Graphics object (see Chapter 7)

7 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-7 The Paint Event Handler - 1 Place the code for the drawing methods in the Paint event handler for the form or control –The Paint event fires each time the form is displayed, resized, moved, maximized, restored, or uncovered –If graphics are drawn in some other method, they will be erased when the Paint event occurs Use the e.Graphics object or declare a Graphics object –Assign the Graphics property of the handler’s PaintEventArgs argument to the new Graphics object

8 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-8 The Paint Event Handler - 2 Write code for the form’s Paint event –Select the form in the Designer –Select the Events button in the Properties window –Select the Paint event private void GraphicsForm_Paint(object sender, PaintEventArgs e) { // Create a graphics object. Graphics gr = e.Graphics; }

9 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-9 The Paint Event Handler - 3 Also create a graphic object by calling the CreateGraphics method of a form or control –Displays a graphic from a method other than the Paint event Graphics gr = this.CreateGraphics(); //Draw on the form. Graphics gr = drawGroupBox.CreateGraphics(); //Draw on a group box control.

10 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-10 Pen and Brush Objects - 1 Each drawing method requires either a pen or brush –Pen Use to draw lines or outlined shapes, such as rectangles or circles Properties: Width, Color –Brush Use to create filled shapes Property: Color

11 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-11 Pen and Brush Objects - 2 Width property –Specifies the width of the stroke of a line or outlined shape created by a Pen object –Specified in pixels Color property –Specifies the color of lines drawn by a Pen object and the color of filled shapes drawn by a Brush object –Assign the color using the Color constants

12 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-12 The Pen Class Default width is one pixel May use several different pens for different colors and/or widths –Or redefine an existing Pen variable if original no longer needed Pen Constructors Pen Examples Pen(Color) Pen(Color, Width) Pen redPen = new Pen(Color.Red); Pen widePen = new Pen(Color.Black, 10);

13 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-13 The SolidBrush Class Use to create filled figures May create one Brush for each color Brush Constructor Brush Example Other brush types: TextureBrush, HatchBrush, LinearGradientBrush, PathGradientBrush SolidBrush(Color) SolidBrush blueBrush = new SolidBrush(Color.Blue);

14 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-14 The Coordinate System Graphics are measured from a starting point of 0,0 for the X and Y coordinates beginning in the upper-left corner of a form or container Most drawing methods allow the position to be specified using –X and Y coordinates –Point structure –Rectangle structure –Size structure X coordinate = horizontal position Y coordinate = vertical position

15 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-15 The Point Structure Holds the X and Y coordinates as a single unit Create a Point object giving it values for the X and Y Use the object anywhere that accepts a Point as an argument Point myStartingPoint = new Point(20, 10);

16 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-16 The Size Structure A Size structure has two components, both specified in pixels –Width (specified first) –Height Use the object anywhere that accepts a Size structure as an argument Size myPictureSize = new Size(100, 20); //Width is 100, height is 20.

17 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-17 The Rectangle Structure Defines a rectangular region, specified by its upper-left corner and its size Overloaded constructor allows a Rectangle to be declared by specifying its X and Y coordinates, width and height Specify PointF, SizeF, and RectangleF structures for float values Rectangle myRectangle = new Rectangle(myStartingPoint, myPictureSize); Rectangle myOtherRectangle = new Rectangle(xInteger, yInteger, widthInteger, heightInteger);

18 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-18 Graphics Methods Two basic categories –Draw Create an outline shape with a Pen object –Fill Create solid shapes with Brush objects Each method requires X and Y coordinates or a Point object Some require the size –Supply as width and height or as a Rectangle object

19 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-19 Graphics Methods - General Form Object.DrawLine(Pen, x1Integer, y1Integer, x2Integer, y2Integer); Object.DrawLine(Pen, Point1, Point2); Object.DrawRectangle(Pen, xInteger, yInteger, widthInteger, heightInteger); Object.DrawRectangle(Pen, Rectangle); Object.FillRectangle(Brush, xInteger, yInteger, widthInteger, heightInteger); Object.FillRectangle(Brush, Rectangle); Object.FillEllipse(Brush, xInteger, yInteger, widthInteger, heightInteger); Object.FillEllipse(Brush, Rectangle);

20 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-20 Graphics Methods - Code Example private void GraphicsForm_Paint(object sender, PaintEventArgs e) { // Draw a red rectangle. e.Graphics.DrawRectangle(Pens.Red, 10, 10, 30, 30); // or Rectangle smallRectangle = new Rectangle(10, 10, 30, 30); e.Graphics.DrawRectangle(Pens.Red, smallRectangle); // Draw a green line. e.Graphics.DrawLine(Pens.Green, 50, 0, 50, 300); // Draw a blue filled circle. e.Graphics.FillEllipse(Brushes.Blue, 100, 100, 50, 50); // Draw a fat blue line. Pen widePen = new Pen(Brushes.Blue, 15); e.Graphics.DrawLine(widePen, 300, 0, 300, 300); }

21 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-21 Selected Methods from the Graphics Class Clear Dispose DrawArc DrawLine DrawEllipse DrawRectangle DrawPie DrawString FillEllipse FillPie FillRectangle

22 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-22 Random Numbers - 1 Use the Random class to create random numbers for games, probability, and queuing theory Random generateRandom = new Random(); To generate a different series of numbers for each run, seed the random number generator by using the system clock –System clock may not work properly on high-performance systems –Seed the Random object yourself by passing an integer value –Use the clock to make sure a different value is passed each time the object instantiates //Seed the random number generator. DateTime currentDateTime = DateTime.Now Random generateRandom = new Random(currentDateTime.Millisecond);

23 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-23 Random Numbers - 2 Seed the Random object once when it is instantiated Generate random numbers using the Random object’s Next method –Returns a positive integer number –Use one of three overloaded arguments to choose the range for the random numbers // Any positive integer number. Object.Next(); // A positive integer up to the value specified. Object.Next(MaximumValueInteger); // A positive integer in the range specified. Object.Next(minimumValueInteger, maximumValueInteger);

24 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-24 Random Numbers - 3 The Random.Next Method – Examples A Random Number Example (Snow) // Return an integer in the range 0 — 10. int generateRandomInteger = generateRandom.Next(10); // Return an integer in the range 1 to the width of the form. int randomNumberInteger = generateRandom.Next(1, this.Width); // Make it snow in random locations. for (int indexInteger = 1; indexInteger < 40000; indexInteger++) { xInteger = generateRandom.Next(1, this.Width); yInteger = generateRandom.Next(1, this.Height); e.Graphics.DrawLine(whitePen, xInteger, yInteger, xInteger + 1, yInteger + 1); }

25 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-25 Simple Animation Possible approaches –Display an animated.gif file in a PictureBox –Replace one graphic with another –Move a picture –Rotate through a series of pictures –Create graphics with various graphics methods On a Web page –Display an animated.gif file –Use a scripting language or embed a Java applet, which creates animation on the client side

26 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-26 Displaying an Animated Graphic On either a Windows Form or a Web Form display an animated.gif file Use a PictureBox control on a Windows Form and an Image control on a Web Form

27 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-27 Controlling Pictures at Run Time Pictures can be added or changed at run time To speed execution, load pictures in controls that can be made invisible –Set Visible property to true when ready to display Use the FromFile method to load a picture at run time Display images from the project Resources folder –ProjectName.Properties.Resources.ResourceName To remove a picture from the display, either hide or use the null constant

28 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-28 Switching Images Easy way to show animation is to replace one picture with another Use images (or icons) of similar sizes and with opposite states (open/closed, up/down, etc.)

29 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-29 Moving a Picture Use the control's SetBounds method –Smoother appearing move than changing Left and Top properties of controls –Can use SetBounds to move a control and change its size –General Form –Examples Object.SetBounds(xInteger, yInteger, widthInteger, heightInteger); planePictureBox.SetBounds(xInteger, yInteger, planeWidth, planeHeight); enginePictureBox.SetBounds(xInteger, yInteger, widthInteger, heightInteger);

30 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-30 The Timer Component - 1 Cause events to occur at a set interval with its Tick event –Code in a Tick event handler executes each time the event occurs Useful for animation; move or change an image each time the Tick event occurs Interval property –Between 0 and 65,535 milliseconds –1,000 milliseconds = 1 second Set value at run time or design time

31 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-31 The Timer Component - 2 Enabled property –false (default) – prevents Tick event from occurring –true – enables the Timer When a timer is added to a form, it goes into the component tray

32 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-32 The Scroll Bar Controls Horizontal scroll bars Vertical scroll bars Use to scroll through a document or a window Used to control sound level, color, size, or other values that can be changed in small or large increments HScrollBar and VScrollBar controls operate independently and have methods, events and properties

33 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-33 Scroll Bar Properties - 1 Minimum for the minimum property Maximum for the maximum property SmallChange –Distance to move when the user clicks the scroll arrows LargeChange –Distance to move when the user clicks the gray area of the scroll bar or presses the Page-Up or Page-Down key

34 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-34 Scroll Bar Properties - 2 Value –Indicates the current position of the scroll box and its corresponding value within the scroll bar –User clicks the up scroll arrow Value property decreases by the amount of SmallChange unless Minimum has been reached –User clicks the down scroll arrow Value property increases by the amount of the SmallChange unless Maximum has been reached

35 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-35 Scroll Bar Events ValueChanged event –Occurs any time the Value property changes, by the user or in code Scroll event –Occurs when the user drags the scroll box –As long as the user continues to drag the scroll box this event continues to occur –When the user releases the mouse button, Scroll events cease and a ValueChanged event occurs Code both a ValueChanged and a Scroll event handler

36 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-36 Playing Sounds Play sound files (.wav) using the SoundPlayer component Set the location of the file using the SoundPlayer’s constructor or its SoundLocation property –SoundPlayer component is in the System.Media library Add a using System.Media statement to the program

37 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-37 Adding Sound Files To use sounds in a project, best to add the files to the project's resources To refer to the filename in code use Namespace.Properties.Resources.Filename Add a sound file to the resources

38 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-38 A Sound-Playing Program Instantiate a SoundPlayer object –Supply the filename in the constructor Execute the SoundPlayer's Play method private void chimesButton_Click(object sender, EventArgs e) { // Play the Chimes.wav file. SoundPlayer myPlayer = new SoundPlayer(Ch13Sounds.Properties.Resources.Chimes); myPlayer.Play(); }

39 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-39 Playing Videos Use the Windows Media Player control –Plays.avi,.wmv, and.wav files

40 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-40 Using the Windows Media Player Control - 1 Add the Windows Media Player control to the toolbox –Right-click on the toolbox –Select Choose Items –Control is located on the Com components tab –Check the box next to the control and press OK The control’s URL property determines file that plays Set path at design time (hard-coded) or at run time –Place files in bin\Debug folder for portability

41 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-41 Using the Windows Media Player Control - 2 Play just sound –Set the visibility to false Allow user to access the Play, Pause and Stop buttons –Set Ctlenabled to true settings.autoStart property –Determines whether loaded file begins playing automatically (default is true)

42 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-42 Drag-and-Drop Programming - 1 Windows users like to use drag-and-drop to make a selection Drag-and-drop begins with a MouseDown event The effect of the drop is determined with a DragEnter event The DragDrop event holds the code for the drop

43 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-43 Drag-and-Drop Programming - 2 The Source object is dragged to the Target object in a drag-and-drop operation

44 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-44 The Source Object Begin a drag-and-drop operation by setting the source object using a control’s DoDragDrop method General Form DragDrop effect specifies requested action –DragDropEffects.Copy, DragDropEffects.Move, DragDropEffects.None Example Object.DoDragDrop(DataToDrag, DesiredDragDropEffect); nameTextBox.DoDragDrop(nameTextBox.SelectedText, DragDropEffects.Move);

45 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-45 The Target Object Location where a user releases the mouse—a drop A form may have multiple targets To allow a form or a control to be a target, set its AllowDrop property to true A target control needs –A DragEnter event handler that sets the effect –A DragDrop event handler that executes the action to take for the drop

46 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-46 The DragEnter Event When a source object is dragged over a target, the target’s DragEnter event fires Assign desired effects to the e argument of the DragEventArgs private void teamBListBox_DragEnter(object sender, DragEventArgs e) { // Set the desired DragDrop effect. e.Effect = DragDropEffects.Move ; }

47 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-47 The DragDrop Event The DragDrop event handler must have code to handle the drop Information being dragged is contained in the Data property of the e argument of the DragDrop event handler Retrieve the dragged data using the GetData method of the Data object –Predefined format for text is DataFormats.Text private void teamBListBox_DragDrop(object sender, DragEventArgs e) { // Add the name to the list box. teamBListBox.Items.Add(e.Data.GetData(DataFormats.Text).ToString()); }

48 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 13-48 Dragging and Dropping an Image Drag and drop images –AllowDrop property of a PictureBox is not available at design time –Set it in the Form_Load event handler targetPictureBox.AllowDrop = true; –Make the drop appear like a move Set the original picture box to null –Make the drop a copy Leave the original alone


Download ppt "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 13 Graphics, Animation, Sound and Drag-and-Drop."

Similar presentations


Ads by Google