Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
Matthew Layton Avatar asked Jan 12 '15 11:01

Matthew Layton


1 Answers

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);
    }
}
like image 95
DonBoitnott Avatar answered Oct 11 '22 07:10

DonBoitnott