LinearGradientBrush does not render correctly

送分小仙女□ 提交于 2019-12-23 08:17:07

问题


Consider the following code from a standard 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);
    }
}

It produces this result:

Why are the red and blue lines showing up in the incorrect order, and how can this be fixed?


回答1:


The rendering origin is the problem. You are asking for a Pen that is 8px wide, and that 8px is defined as outward 4px in both directions from the line defined by your rectangle. That is due to the default value of Alignment=Center. If you set the Pen to use Alignment=Inset, you will have better results.

You can see this line by simply adding this to your original code:

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

Change your method to be this, and it will work:

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


来源:https://stackoverflow.com/questions/27901068/lineargradientbrush-does-not-render-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!