GDI + .NET:宽度超过202像素的LinearGradientBrush导致颜色环绕

时间:2011-11-04 20:59:16

标签: .net winforms graphics gdi+

如果我使用LinearGradientBrush绘制一个宽度超过202像素的矩形,我会在左边看到一个彩色条纹:

enter image description here

给出 202px 宽矩形的代码:

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);
}

我得到一个正确绘制的矩形:

enter image description here

但如果我将矩形更改为 203 像素宽:

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

矩形在左侧有一个彩色条纹或环绕:

enter image description here


它也发生在垂直方向LinearGradientMode.Vertical

202px

enter image description here

203px

enter image description here

1 个答案:

答案 0 :(得分:11)

在FillRectangle()调用之前添加此语句:

 e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

这可以避免因浮点舍入错误导致的逐个问题。

相关问题