Search code examples
c#system.drawing

Create a polygon filled with a tiled image in c#


I'm creating an application which visualises a picture frame as the user designs it. To create the frame I am drawing 4 polygons which represent the physical bits of wood and using a TextureBrush to fill it.

This works perfectly well for the left and top edges. However, for the bottom and right edges this method isn't working. It appears to me that the TextureBrush is tiling from the point (0,0) on the image and not within the polygon I've drawn. As a result, the tile doesn't line up with the polygon. By adjusting the size of the image I can get the tile to line up perfectly.

How do I create an arbitrarily positioned polygon and fill it with a tiled image, starting from the point (0,0) within the polygon, not the canvas?

I'm not attached to FillPolygon and TextureBrush if there is a better solution.

Example

alt text


Solution

  • I've just found the answer. I was playing with adding a BoundingBox to the TextureBrush constructor but I kept getting OutOfMemory exceptions and thought it was me not understanding. Turns out it's a bug in the .NET framework

    http://connect.microsoft.com/VisualStudio/feedback/details/90973/texturebrush-constructor-throws-out-of-memory-exception-when-providing-the-bounding-rectangle

    The work around is to use a transformation to move the texture

    var brush = new TextureBrush(new Bitmap(imagefile));
    
    Matrix mtx = brush.Transform;
    mtx.Translate(xoffset, 0);
    brush.Transform = mtx;