Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GDI+ .NET: LinearGradientBrush wider than 202 pixels causes color wrap-around

If i paint a rectangle that is wider than 202 pixels wide with a LinearGradientBrush, i get a color fringe on the left:

enter image description here

Given the code for a 202px wide rectangle:

private void MainForm_Paint(object sender, PaintEventArgs e)
{
   Rectangle r = new Rectangle(50, 50, 202, 50);

   Color color1 = Color.FromArgb(unchecked((int)0xFF00024d));
   Color color2 = Color.FromArgb(unchecked((int)0xFFd6a20f));

   Brush b = new LinearGradientBrush(r, color1, color2, LinearGradientMode.Horizontal);
   e.Graphics.FillRectangle(b, r);
}

i get a rectangle that paints correctly:

enter image description here

But if i change the rectangle to be 203 pixels wide:

Rectangle r = new Rectangle(50, 50, 203, 50);

The rectangle has a color fringe, or wrap-around, on the left:

enter image description here


It also happens in the vertical direction with LinearGradientMode.Vertical:

202px:

enter image description here

203px:

enter image description here

like image 952
Ian Boyd Avatar asked Nov 04 '11 20:11

Ian Boyd


1 Answers

Add this statement before the FillRectangle() call:

 e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

That avoids off-by-one problems due to floating point rounding error.

like image 95
Hans Passant Avatar answered Sep 20 '22 01:09

Hans Passant