Tile a PictureBox in C#

[tile]

If you set a form’s BackgroundImageLayout property Tile, then the control fills itself with copies of its background image. Strangely the PictureBox control does not have a corresponding Tile property. This example shows one way you can tile images on a PictureBox.

The example’s PictureBox has Anchor property set so it resizes when the form does. The following form Resize event handler refreshes the PictureBox.

// Refresh the PictureBox.
private void Form1_Resize(object sender, EventArgs e)
{
    picTile.Refresh();
}

The example uses the form’s Resize event instead of the PictureBox control’s event because that event sometimes causes strange behavior.

The following code shows the PictureBox control’s Paint event handler.

// Tile the image.
private void picTile_Paint(object sender, PaintEventArgs e)
{
    using (TextureBrush brush =
        new TextureBrush(Properties.Resources.Smiley))
    {
        e.Graphics.FillRectangle(brush, picTile.ClientRectangle);
    }
}

At design time I used the Project > Properties > Resources to create a resource holding the Smiley image. The Paint event handler uses that image to create a TextureBrush. It then uses that brush to fill the PictureBox control’s client area.

If you wanted the program to draw something such as lines or other shapes on top of the images, it could do so after it fills the client rectangle.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics, image processing and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *