# Can SpriteBatch be used to fill a polygon with a texture?

I basically need to fill a texture into a polygon using the SpriteBatch. I've done some research but couldn't find anything useful except polygon triangulation method, which works well only with convex polygons (without diving into super math which is definitely not something I'm pretty good at). Are there any solutions for filling in a polygon in a basic way? I of course need something dynamic (I'll have a map editor that you can define polygons, and the game will render them (and collision detection will also use them but that's off topic), basically I can't accept solutions like "pre-calculated" bitmaps or anything like that. I need to draw a polygon with the segments provided, to the screen, using the SpriteBatch.

-

private Bitmap ClippedBitmap(Bitmap texture, Point[] pointsArray, out Point position)
{
int minX = pointsArray.Min(x => x.X);
int maxX = pointsArray.Max(x => x.X);
int minY = pointsArray.Min(x => x.Y);
int maxY = pointsArray.Max(x => x.Y);
position = new Point(minX, minY);
Bitmap bit = new Bitmap(maxX - minX, maxY - minY);
Point[] offset = new Point[pointsArray.Length];
pointsArray.CopyTo(offset, 0);
offset = Array.ConvertAll(offset, x=> x = new Point(x.X - minX,x.Y - minY));
Graphics g = Graphics.FromImage(bit);
TextureBrush tb = new TextureBrush(texture);
g.FillPolygon(tb, offset);
return bit;
}

Load the texture U need as a bitmap, then use this. pointsArray is a polygon points. Point position is a position point, where you ought to draw the texture to be fitted in polygon. Also, you can add code

tb.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;

float scaleFactor = Math.Max((float)bit.Width / texture.Width, (float)bit.Height / texture.Height);

tb.ScaleTransform(scaleFactor, scaleFactor);

if you want to wrap your texture inside the polygon (otherwise if will be tilted).

-

if you have to use the spritebatch, only accepts to draw rectangles, and you define the polygon in a map editor, why don't precalc the texture?

You can still use your polygon for physics, only have to create its skin.

1. Create a new texture. The polygon have to fit inside.
2. Fill the texture with Color.TransparentBlack
3. Draw the polygon's edges with lines. You can use the bresenham algoritm
4. Do a flood fill with your texture.
5. Then you save this new texture.
6. Later inside the game you can draw with this new texture as a rectangle

Other approach is to compose the polygon with triangles, but that it's not worth.

And the third option is not using spritebatch and triangulize as you know

-