GDI + .NET:一个LinearGradientBrush比202像素更宽导致颜色环绕像素、颜色、NET、GDI

2023-09-03 05:16:32 作者:从此深情都喂了狗

如果我画一个矩形,宽度大于202像素宽以一个LinearGradientBrush ,我得到左边的彩色条纹:

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

由于$ C $下一个 202px 宽的矩形:

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:

但是,如果我改变矩形是 203 像素宽:

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:

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

202px

203px

推荐答案

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

Add this statement before the FillRectangle() call:

 e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

这避免了断接一个问题,是由于浮点舍入误差。

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