GDI+ .NET: LinearGradientBrush wider than 202 pixe

2019-02-22 10:10发布

问题:

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

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:

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:


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

202px:

203px:

回答1:

Add this statement before the FillRectangle() call:

 e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

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