Sign in to follow this  

[C#] Rectangle filled with Texture

Recommended Posts

HI there. I have made a small class which creates a small drag box when a mouse is clicked a dragged, commonly used to select multiple items.
//Here is how I draw it :
public void DrawBox()
            //Draw a Box with Specified with/Height at mousepos
            if (MousePressed)
                Rectangle areaRect = new Rectangle(
                    (int)(currMousePos.X - StartMousePos.X),
                    (int)(currMousePos.Y - StartMousePos.Y));
                batchRef.Draw(texture, areaRect, Color.White);

//this is the Texture creation if its relevant :)
private void CreateTexture()
            texture = new Texture2D(dDevice, 1, 1, 1, TextureUsage.None, SurfaceFormat.Color);
            Color myColor = new Color(box_bgColor.R, box_bgColor.G, box_bgColor.B, boxTransparency);
            texture.SetData<Color>(new Color[] { myColor });                       

so far it works well. However, it will only draw if the area of the rectangle if Negative (e.g. there is a -width and positive height). And nothing is draw when there is a positive area. (e.g. both width and height are positive and negative) Is this because I am drawing the rectangle incorrectly? or is it because of something XNA does to draw it? or am I simply being ignorant with my maths :P

Share this post

Link to post
Share on other sites
If you use the spritebatch, it acts as if you drew 4 vertices to form the quad on which the rectangle is drawn, and the drawn Texture2D is the texture placed on those 4 points.
There is something called CullMode in GraphicsDevice.RenderState. It defines which triangles to draw. By default, only those triangles that are drawn clockwise will really get drawn. So if your mouse goes in the negative direction, the triangles would be in counterclockwise order, so they won't be drawn.

Try setting GraphicsDevice.RenderState.CullMode to CullMode.None and try again.
If you don't want to set this setting, you can also flip your drawn images, see the spritebatch overloads on how to do that.

I personally would recalculate the top left point and the size of the rectangle each time Update gets called.


Maybe this little picture helps you. It shows the order of the created vertices.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this