LinearGradientBrush 无法正确呈现

LinearGradientBrush does not render correctly

从标准 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);
    }
}

它产生这个结果:

为什么红线和蓝线的显示顺序不正确,如何解决?

渲染原点有问题。您要求 Pen 宽度为 8px,并且该 8px 被定义为从矩形定义的线向外两个方向的 4px。这是由于 Alignment=Center 的默认值。如果你设置Pen使用Alignment=Inset,你会得到更好的结果。

您只需将此添加到您的原始代码即可看到这一行:

e.Graphics.DrawRectangle(Pens.White, test);

将你的方法改成这样,它会起作用:

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