Loading, Displaying and Scaling Images
C#'s multimedia capabilities include graphics, images, animations and video. Previous sections demonstrated C#'s vector-graphics capabilities; this section presents image manipulation. The application in Fig. 17.23 loads an Image (System.Drawing namespace), then allows the user to scale the Image to a specified width and height.
Figure 17.23. Image resizing.
1 // Fig. 17.23: DisplayLogoForm.cs
2 // Displaying and resizing an image
3 using System;
4 using System.Drawing;
5 using System.Windows.Forms;
6
7 // displays an image and allows the user to resize it
8 public partial class DisplayLogoForm : Form
9 {
10 private Image image = Image.FromFile( @"imagesLogo.gif" );
11 private Graphics graphicsObject;
12
13 public DisplayLogoForm()
14 {
15 InitializeComponent();
16 graphicsObject = this.CreateGraphics();
17 }
18
19 // handle setButton Click event
20 private void setButton_Click( object sender, EventArgs e )
21 {
22 // get user input
23 int width = Convert.ToInt32( widthTextBox.Text );
24 int height = Convert.ToInt32( heightTextBox.Text );
25
26 // if dimensions specified are too large 27 // display problem 28 if ( width > 375 || height > 225 ) 29 { 30 MessageBox.Show( " Height or Width too large" ); 31 return; 32 } // end if 33 34 // clear the Form then draw the image 35 graphicsObject.Clear( this.BackColor ); 36 graphicsObject.DrawImage( image, 5, 5, width, height ); 37 } // end method setButton_Click 38 } // end class DisplayLogoForm
|
Line 10 declares Image variable image and uses static Image method FromFile to load an image from a file on disk. Line 16 uses the Form's CreateGraphics method to create a Graphics object for drawing on the Form. Method CreateGraphics is inherited from class Control. When you click the Set Button, lines 2832 validate the width and height to ensure that they are not too large. If the parameters are valid, line 35 calls Graphics method Clear to paint the entire Form in the current background color. Line 36 calls Graphics method DrawImage, passing as arguments the image to draw, the x-coordinate of the image's upper-left corner, the y-coordinate of the image's upper-left corner, the width of the image and the height of the image. If the width and height do not correspond to the image's original dimensions, the image is scaled to fit the new width and height.
Animating a Series of Images
|