【问题标题】:C# LinearGradientBrush. How can I change the point where the two colors blend?C# 线性渐变画笔。如何更改两种颜色混合的点?
【发布时间】:2017-03-17 15:35:09
【问题描述】:

我有这段代码可以让我在我的 windows 窗体中添加一些混合:

public partial class Form1 : Form
{
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, 
               Color.White, 
               Color.Black, 
               LinearGradientMode.Vertical))
        {
            e.Graphics.FillRectangle(brush, this.ClientRectangle);
        }
    }
}

结果如下:

默认情况下,两种颜色混合的“峰值”正好在方框的中间。我想调整代码,使混合的“峰值”出现在顶部的大约 3/4 处。是否可以更改两种颜色开始混合的点?

提前谢谢你。

【问题讨论】:

    标签: c# winforms lineargradientbrush


    【解决方案1】:

    您可以将画笔的InterpolationColors属性设置为合适的ColorBlend,例如:

    using (var brush = new LinearGradientBrush(this.ClientRectangle,
        Color.Transparent, Color.Transparent, LinearGradientMode.Vertical))
    {
        var blend = new ColorBlend();
        blend.Positions = new[] { 0, 3 / 4f, 1 };
        blend.Colors = new[] { Color.White, Color.Black, Color.Black };
        brush.InterpolationColors = blend;
        e.Graphics.FillRectangle(brush, this.ClientRectangle);
    }
    

    或者例如另一种混合:

    blend.Positions = new[] { 0, 1 / 2f, 1 };
    blend.Colors = new[] { Color.White, Color.Gray, Color.Black };
    

    【讨论】:

    • 颜色混合的方式比原始代码好得多。谢谢雷扎。
    最近更新 更多