PictureBoxes

A PictureBox displays an image. The image can be one of several formats, such as bitmap, GIF (Graphics Interchange Format) and JPEG. (Images are discussed in Chapter 17, Graphics and Multimedia.) A PictureBox's Image property specifies the image that is displayed, and the SizeMode property indicates how the image is displayed (Normal, StretchImage, Autosize or CenterImage). Figure 13.29 describes common PictureBox properties and a common event.

Figure 13.29. PictureBox properties and event.

PictureBox properties and event

Description

Common Properties

Image

Sets the image to display in the PictureBox.

SizeMode

Enumeration that controls image sizing and positioning. Values are Normal (default), StretchImage, AutoSize and CenterImage. Normal places the image in the top-left corner of the PictureBox, and CenterImage puts the image in the middle. These two options truncate the image if it is too large. StretchImage resizes the image to fit in the PictureBox. AutoSize resizes the PictureBox to hold the image.

Common Event

Click

Occurs when the user clicks the control. When you double click this control in the designer, an event handler is generated for this event.

Figure 13.30 uses a PictureBox named imagePictureBox to display one of three bitmap imagesimage0, image1 or image2. These images are located in the images directory in the project's bin/Debug and bin/Release directories. Whenever a user clicks the Next Image Button, the image changes to the next image in sequence. When the last image is displayed and the user clicks the Next Image Button, the first image is displayed again. Inside event handler nextButton_Click (lines 2028), we use an int (imageNum) to store the number of the image we want to display. We then set the Image property of imagePictureBox to an Image (lines 2527).

Figure 13.30. Using a PictureBox to display images.

(This item is displayed on pages 627 - 628 in the print version)

1 // Fig. 13.30: PictureBoxTestForm.cs 2 // Using a PictureBox to display images. 3 using System; 4 using System.Drawing; 5 using System.Windows.Forms; 6 using System.IO; 7 8 // Form to display different images when PictureBox is clicked 9 public partial class PictureBoxTestForm : Form 10 { 11 private int imageNum = -1; // determines which image is displayed 12 13 // default constructor 14 public PictureBoxTestForm() 15 { 16 InitializeComponent(); 17 } // end constructor 18 19 // change image whenever Next Button is clicked 20 private void nextButton_Click( object sender, EventArgs e ) 21 { 22 imageNum = ( imageNum + 1 ) % 3; // imageNum cycles from 0 to 2 23 24 // create Image object from file, display in PicutreBox 25 imagePictureBox.Image = Image.FromFile( 26 Directory.GetCurrentDirectory() + @"imagesimage" + 27 imageNum + ".bmp" ); 28 } // end method nextButton_Click 29 } // end class PictureBoxTestForm  

(a)

(b)

(c)

Категории