Title: Tile a PictureBox in C#
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 the example to experiment with it and to see additional details.
|