Tiling an image within a rectangle (GDI+)

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

I'm trying to write a routine to tile a given image in a given rectangle:

public static void DrawTiledImage(Graphics g, Image image, Rectangle r)
{
ImageAttributes ia = new ImageAttributes();
ia.SetWrapMode(WrapMode.Tile);
g.DrawImage(image, r, 0, 0, image.Width, image.Height,
GraphicsUnit.Pixel, ia);
}

Problem is this seems to be stretching the image not tiling it. What am I
doing wrong ?
 
Just make your source rectangle larger than your image.

For example:
public static void DrawTiledImage(Graphics g, Image image, Rectangle r)
{
ImageAttributes ia = new ImageAttributes();
ia.SetWrapMode(WrapMode.Tile);
g.DrawImage(image, r, 0, 0, 4*image.Width, 4*image.Height,
GraphicsUnit.Pixel, ia);
}
 
JezB said:
I'm trying to write a routine to tile a given image in a given rectangle:

The snippet below should point you into the right direction:

\\\
Private m_Brush As TextureBrush

Private Sub Form1_Load(...) Handles MyBase.Load
m_Brush = New TextureBrush(New Bitmap("C:\WINDOWS\Angler.bmp"))
End Sub

Protected Overrides Sub OnPaintBackground(ByVal e As PaintEventArgs)
MyBase.OnPaintBackground(e)
e.Graphics.FillRectangle(m_Brush, Me.ClientRectangle)
End Sub
///
 
This does not quite work, in that the image does not always start at the top
left pixel within the target rectangle. While this is not always important,
it is in my case.
 
While I do not quite understand why this should work, it does, up to a
point. Actually I find that since my image is 1 pixel wide and 21 high,
inflating just the source width and not the height has the desired effect. I
was hoping to write a routine that is a bit more generic for tiling any
image within any rectangle though.
 
Back
Top