Search code examples
c#drawrectangle

Partially fill a Rectangle object


I was wondering if it's possible to fill a certain percentage of a Rectangle object that's been draw on-screen so that it behaves like a Progress Bar, where you can watch its "level" go up and down. Specifically, I'd like to fill it from top to bottom rather than left to right.


Solution

  • You can try this.

    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Width = 400;
        panel1.Height = 50;
    
        using (Graphics g = this.panel1.CreateGraphics()) 
        {
            g.Clear(Color.Black);
            Pen pen = new Pen(Color.Red, 2);               
            for (int i = 0; i <= 50;i++ )
            {
                g.DrawRectangle(pen, 0, 0, 400, i);                    
                Thread.Sleep(100);
            }                   
            pen.Dispose();
        }
    }