LinearGradientBrush无法正确呈现 [英] LinearGradientBrush does not render correctly

查看:241
本文介绍了LinearGradientBrush无法正确呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下来自标准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);
    }
}

它产生以下结果:

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

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

推荐答案

渲染来源是问题所在.您要的是Pen,宽度为8px,并且将8px定义为从矩形所定义的线的两个方向上的向外4px.这是由于默认值Alignment=Center.如果将Pen设置为使用Alignment=Inset,则效果会更好.

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

这篇关于LinearGradientBrush无法正确呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆