Многоцветный линейный градиент в WinForms - PullRequest
19 голосов
/ 19 октября 2011

Как создать многоцветный линейный градиент в WinForms? System.Drawing.Drawing2D.LinearGradientBrush позволяет использовать только два цвета.

Ответы [ 2 ]

53 голосов
/ 07 декабря 2011

тот же ответ, что и здесь: Многоцветный диагональный градиент в winforms Многоцветный диагональный градиент в winforms

Вот небольшой пример

void MainFormPaint(object sender, PaintEventArgs e)
{
  LinearGradientBrush br = new LinearGradientBrush(this.ClientRectangle, Color.Black, Color.Black, 0 , false);
  ColorBlend cb = new ColorBlend();
  cb.Positions = new[] {0, 1/6f, 2/6f, 3/6f, 4/6f, 5/6f, 1};
  cb.Colors = new[] {Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet};
  br.InterpolationColors= cb;
  // rotate
  br.RotateTransform(45);
  // paint
  e.Graphics.FillRectangle(br, this.ClientRectangle);
}

вот результат

enter image description here

надеюсь, это поможет

0 голосов

Я создал панель, так как я могу использовать ее в качестве контейнера для своего проекта. Код действительно прост, то есть если вы хотите реализовать без остановок, как это предусмотрено Punker76.

public partial class GradientPanel : Panel
{
    private Color _startColor = Color.Transparent;
    private Color _stopColor = Color.Transparent;
    private bool _angleScales = false;
    private int _angle = 0;


    /// <summary>
    /// litle helper to redraw when property changes, a litle OnNofifyChanged for the 
    /// IDE causing it to update
    /// </summary>
    /// <typeparam name="T">Making sure the values are comparable</typeparam>
    /// <param name="field">the field that is compared</param>
    /// <param name="value">the value that is assigned</param>
    /// <remarks>Updates re-paints the panel when needed</remarks>
    private void Set<T>(ref T field, T value)
    {
        if (field.Equals(value))
            return;
        field = value;
        base.Refresh();
    }

    [Category("Appearence"),Description("Specifies the start colour")]
    public Color StartColor  {    get => _startColor;  set => Set(ref _startColor, value); }

    [Category("Appearence"), Description("Specifies the stop colour")]
    public Color StopColor { get => _stopColor; set => Set(ref _stopColor, value); }

    [Category("Appearence"), Description("The angle, measured in degrees clockwise from the x-axis, of the gradient's orientation line.")]
    public int Angle { get => _angle; set => Set(ref _angle , value);        }

    [Category("Appearence"), Description("If Set to true to specify that the angle is affected by the transform associated with this panel")]        
    public bool AngleScales { get => _angleScales; set => Set(ref _angleScales, value); }

    protected override void OnPaint(PaintEventArgs e)
    {

        LinearGradientBrush br = new LinearGradientBrush(e.ClipRectangle, StartColor, StopColor, Angle, AngleScales);
        e.Graphics.FillRectangle(br, e.ClipRectangle);
        base.OnPaint(e);
    }
}

Наличие контроля делает повторное использование намного более эффективным. Помните, что вам может потребоваться пересмотреть проект, прежде чем вы увидите, как изменения вступают в силу при внесении изменений в элемент управления.

...