多色渐变不显示所有颜色

Multi-color gradient does not show all colors

我有一个多色渐变,它由 14 种颜色组成。这是我的代码:

panel1.Paint += new PaintEventHandler(panel1_Paint);
panel1.Refresh();

private void panel1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;

    LinearGradientBrush br = new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(255, 0, 0, 0), Color.FromArgb(255, 100, 100, 200),0, false);
    System.Drawing.Drawing2D.ColorBlend cb = new System.Drawing.Drawing2D.ColorBlend();
    cb.Positions = new[] { 0, 1 /15f, 2 / 15f, 3 / 15f, 4 / 15f, 5 / 15f, 6 / 15f, 7 / 15f, 8 / 15f, 9 / 15f, 10 / 15f, 11 / 15f, 12 / 15f, 13 / 15f,1 };

    cb.Colors = new[] {
        Color.FromArgb(255, 0, 0, 0),
        Color.FromArgb(255, 0, 0, 50),
        Color.FromArgb(255, 10, 10, 100),
        Color.FromArgb(255, 30, 30, 100),
        Color.FromArgb(255, 70, 70,200),
        Color.FromArgb(255, 100, 100, 255),
        Color.FromArgb(255, 170, 170, 255),
        Color.FromArgb(255, 55, 151, 107),
        Color.FromArgb(255, 117, 194, 103),
        Color.FromArgb(255, 230, 230, 128),
        Color.FromArgb(255, 202, 157, 75),
        Color.FromArgb(255, 185, 154, 100),
        Color.FromArgb(255, 220, 220, 220),
        Color.FromArgb(255, 255, 255, 255),
        Color.FromArgb(255, 100, 100, 200) };

    br.InterpolationColors = cb;
    // rotate
    br.RotateTransform(90);
    // paint
    g.FillRectangle(br, this.ClientRectangle);
}

遗憾的是它没有显示所有颜色。我的矩形的高度是 100,但它显示了这样的渐变:

出了什么问题,我该如何解决?

如果要垂直填充矩形,应在 LinearGradientBrush:

的构造函数中指定旋转
new LinearGradientBrush(this.ClientRectangle, colorFrom, colorTo, 90, false);
                                                           Here --^

并删除转换

br.RotateTransform(90);

由于 ClientRectangle 的宽度和高度基本上被您当前的实现交换了(因为 90° 旋转),您要么只看到渐变的一小部分,要么多次看到整个渐变。

这个也不行,因为你用错了ClientRectangle。您在表单的 code-behind 中使用了 this.ClientRectangle。将每个 this.ClientRectangle 替换为 panel1.ClientRectangle.

这看起来应该如何:

您未修改的代码的外观: