c# - 面板背景漆不起作用

标签 c# winforms gradient paint

我一直在用面板做我的 winforms 的边框。我想在我的底部面板中使用渐变,但我遇到了问题。

我使用的方法几乎与我在此处绘制表单背景时使用的方法相同,但我在面板中得到了一个红叉。我不知道为什么会这样,它应该可以正常工作。

图片:enter image description here

这是我要绘制的代码:

public void Colorear_Barra_abajo(object sender, PaintEventArgs e)
    {
        Rectangle r = this.ClientRectangle;

        if (r.Width > 0 && r.Height > 0)
        {
            Color c1 = Color.FromArgb(255, 54, 54, 54);
            Color c2 = Color.FromArgb(255, 98, 98, 98);

            LinearGradientBrush br = new LinearGradientBrush(r, c1, c2, 90, true);
            ColorBlend cb = new ColorBlend();
            cb.Positions = new[] { (float)0.357, (float)0.914 };
            cb.Colors = new[] { c1, c2 };
            br.InterpolationColors = cb;

            // paint
            e.Graphics.FillRectangle(br, r);
        }
    }

这就是我的称呼(panel_Borde_abajo 是面板):

public Base_Form_Standard()
    {
        InitializeComponent();
        panel_Borde_abajo.Paint += new PaintEventHandler(Colorear_Barra_abajo);
    }

我曾经使用这种方法来绘制表单以外的其他控件(menustrip f.e)并且它们工作正常,但是这个特别的方法不起作用。

例如,这确实可以正常工作并且没有出现红叉:

public void Form_Background(object sender, PaintEventArgs e)
    {
        Rectangle r = this.ClientRectangle;

        if (r.Width > 0 && r.Height > 0)
        {
            Color c1 = Color.FromArgb(255, 252, 254, 255);
            Color c2 = Color.FromArgb(255, 247, 251, 253);
            Color c3 = Color.FromArgb(255, 228, 239, 247);
            Color c4 = Color.FromArgb(255, 217, 228, 238);
            Color c5 = Color.FromArgb(255, 177, 198, 215);

            LinearGradientBrush br = new LinearGradientBrush(r, c1, c5, 90, true);
            ColorBlend cb = new ColorBlend();
            cb.Positions = new[] { 0, (float)0.3, (float)0.486, (float)0.786, 1 };
            cb.Colors = new[] { c1, c2, c3, c4, c5 };
            br.InterpolationColors = cb;

            // paint
            e.Graphics.FillRectangle(br, r);
        }
    }

如果有人能帮助我,那就太好了!

最佳答案

看起来,您为 ColorBlend.Positions 属性使用了无效值,请尝试以下代码:

ColorBlend cb = new ColorBlend();
cb.Positions = new[] { 0.0f, 0.357f, 0.914f, 1.0f };
                       ^^^^                  ^^^^

根据documentation :

The elements in this array are represented by float values between 0.0f and 1.0f, and the first element of the array must be 0.0f and the last element must be 1.0f.

关于c# - 面板背景漆不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14005141/

相关文章:

c# - 如何检测 WinForms 中 NumericUpDown 字段的用户更改?

c# - 是否可以从 PropertyGrid 中隐藏枚举值?

c# - 在禁用时记住控件的文本

ios - 加载后具有不同大小的 UIButton

ios - 将渐变应用于虚线 UIBezierPath

c# - Autofac:注册 Func<> 或工厂?

c# - 调用 INotifyPropertyChanged 的​​ PropertyChanged 事件的最佳方式是什么?

c# - Entity Framework 5 代码优先多对多表重命名继承类 (TPC)

c# - 如何检查 appSettings 键是否存在?

android - 向渐变添加百分比