Search code examples
c#winformsgdi+gdi

LinearGradientBrush does not render correctly


Consider the following code from a standard System.Windows.Forms.Form

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Rectangle test = new Rectangle(50, 50, 100, 100);
    using (LinearGradientBrush brush = new LinearGradientBrush(test, Color.Red, Color.Blue, 0f))
    {
        e.Graphics.DrawRectangle(new Pen(brush, 8), test);
    }
}

It produces this result:

enter image description here

Why are the red and blue lines showing up in the incorrect order, and how can this be fixed?


Solution

  • The rendering origin is the problem. You are asking for a Pen that is 8px wide, and that 8px is defined as outward 4px in both directions from the line defined by your rectangle. That is due to the default value of Alignment=Center. If you set the Pen to use Alignment=Inset, you will have better results.

    You can see this line by simply adding this to your original code:

    e.Graphics.DrawRectangle(Pens.White, test);
    

    Change your method to be this, and it will work:

    Rectangle test = new Rectangle(50, 50, 100, 100);
    using (LinearGradientBrush brush = new LinearGradientBrush(test, Color.Red, Color.Blue, 0f))
    {
        using (var pen = new Pen(brush, 8f))
        {
            pen.Alignment = PenAlignment.Inset;
            e.Graphics.DrawRectangle(pen, test);
        }
    }