考虑来自标准 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);
}
}
它产生这样的结果:
为什么红线和蓝线的显示顺序不正确,如何解决?
最佳答案
渲染源是问题所在。您需要一个 8px 宽的 Pen
,并且该 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);
}
}
关于c# - LinearGradientBrush 无法正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901068/