Tiling an image within a rectangle (GDI+)

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 ?
 
M

Michael Phillips, Jr.

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);
}
 
H

Herfried K. Wagner [MVP]

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
///
 
J

JezB

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.
 
J

JezB

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top