Displaying Images in Forms

We can include graphics images in a form. There are several formats for graphics images, but this account deals primarily with bitmap images (extension "bmp") which are quite widely used in Windows. A bitmap file is stored in a "lossless" fashion, basically storing a color value for each pixel ("raster" graphics). The actual file format contains various other data as well. A bitmap adapts well to different resolutions but does not necessarily scale well.


Image Class

This is an abstract base class for other classes such as Bitmap.

Properties (some of them)

Methods (one of them)

     public static Image FromFile(String Filename)

This creates an Image from the file.

There are various other "From" methods to create an Image from other sources.


Bitmap Class

This represents one Image specifically created from a bitmap file.

Constructors (a few of them)

Properties

We have Width, Height and Size (and more), inherited from Image.


How do we display the image

We will need a Graphics object:

     Graphics G = this.CreateGraphics();

After that, we can use any of several methods. Here are a few:


TextureBrush Class

The TextureBrush class is derived from the Brush class and is used for "tiling".

Sometimes we want to use an image as a background, filling a space with copies of the image side by side. This is called tiling.

Constructors (a couple of them)

Here WrapMode indicates a member of the WrapMode enumerated type, which includes values such as:


Examples

     // This draws the image at the given location.
     Graphics G = this.CreateGraphics();
     Bitmap B = new Bitmap("A_Picture.bmp");
     DrawImage(B, 100, 100);

     // This fills a rectangle with copies of the image.
     Graphics G = this.CreateGraphics();
     Bitmap B = new Bitmap("A_Picture.bmp");
     TextureBrush TB = new TextureBrush(B, WrapMode.Tile);
     Rectangle R = new Rectangle(20, 20, 500, 500);
     G.FillRectangle(TB, R);

     // This fills a rectangle with copies of the image with
     // horizontal flipping.
     Graphics G = this.CreateGraphics();
     Bitmap B = new Bitmap("A_Picture.bmp");
     TextureBrush TB = new TextureBrush(B, WrapMode.TileFlipX);
     Rectangle R = new Rectangle(20, 20, 500, 500);
     G.FillRectangle(TB, R);


PictureBox class

The PictureBox is used to display an image from a file such as bitmap, JPEG, GIF, pNG or some others.

PictureClass has various properties, such as:

Example (adapted from a MSDN page):

private Bitmap MyImage;

public void ShowMyImage(String fileToDisplay, int xSize, int ySize)
{
   // Stretches the image to fit the pictureBox.
   pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
   MyImage = new Bitmap(fileToDisplay);
   pictureBox1.ClientSize = new Size(xSize, ySize);
   pictureBox1.Image = (Image) MyImage;
}