As the title states, I’m trying to resize a Texture2D before even considering SpriteBatch.Draw(). The reason I’m doing this is I’m trying to fill an arbitrary polygon, laid out with vertices defined by Vector2Ds, with an arbitrary Texture2D.
What I’m thinking of is creating the rectangle that fits the polygon, scaling the Texture2D to that rectangle, and then making the pixels that are outside of the polygon transparent via Texture2D‘s GetData<>() and SetData<>().
I’ve gotten to the point of finding the rectangle that fits the polygon, but is there a way to resize the Texture2D, or am I going about it the completely wrong way? Thanks!
You’re going about it the wrong way. Setting texture data is expensive. (And there’s probably some issues with filtering, too.)
What you want to do is set the texture coordinates (the “UV coordinates”) of the vertices you are drawing. This will cause a specific location of your texture to appear at that vertex of your polygon. The texture that would then fall outside your polygon is simply never drawn (it is “clipped” by the polygon edges).
Texture coordinates are specified in the range 0.0 to 1.0 (on the U and V axies – horizontally and vertically) from the top left to the bottom right of your texture.
If you are drawing using vertex buffers, XNA includes some built-in vertex structures like
VertexPositionTextureandVertexPositionColorTexturethat allow you to specify aTextureCoordinatevalue.If you are using your own vertex structure, use
VertexElementUsage.TextureCoordinatewhen specifying aVertexElement. If you are creating your own shader, the value will be exposed inTEXCOORD0(for usage index 0).If you are just drawing rectangles with
SpriteBatch, then specify asourceRectanglewhen you callDraw.