Search code examples
c#.net-coregraphicsdrawrectangle

Drawing a filled rectangle in C# .NET Core


I want to make a rectangle with a custom filled colour (background colour) and a line

private void FooMethod(Graphics graph)
{
   // Draw a simple rectangle in C#, not filled.
   Rectangle rect = new Rectangle(0, 0, 100, 45);
   graph.DrawRectangle(Pens.Black, rect);
   
   // "Make"? a filled rectangle (it doesn't work)
   graph.FillRectangle(Brushes.White); // I don't know how to proceed to draw a filled rectangle.
}

But It doesn't work and I tried this Microsoft post and what I have showed (I'm too lazy to show you the Microsoft code but you can see with the link.

(I don't have much time to write, sorry if it's too short)


Solution

  • You fill first and draw after so it won't get drawn over

        void FooMethod(Graphics graph)
        {
            Rectangle rectangle = new Rectangle(5, 5, 100, 45);
    
            graph.FillRectangle(Brushes.White, rectangle);
            graph.DrawRectangle(Pens.Black, rectangle);
        }
    

    if you have a more complex shape, I suggest you use a GraphicsPath

        void FooMethod(Graphics graph)
        {
            Rectangle rectangle = new Rectangle(5, 5, 100, 45);
            GraphicsPath path = new GraphicsPath();
            path.AddRectangle(rectangle);
            // add to the  path
            graph.FillPath(Brushes.White, path);
            graph.DrawPath(Pens.Black, path);
        }
    

    Here is a path that includes a rectangle and an ellipse as a hole

    scr1

        void FooMethod(Graphics graph)
        {
            using(GraphicsPath path = new GraphicsPath())
            {
                Rectangle rectangle = new Rectangle(5, 5, 100, 45);
                path.AddRectangle(rectangle);
                rectangle.Inflate(-5, -5);
                path.AddEllipse(rectangle);
                graph.FillPath(Brushes.White, path);
                graph.DrawPath(Pens.Black, path);
            }
        }