Creates a gradient brush from a list of colors. - CSharp System.Drawing

CSharp examples for System.Drawing:Color

Description

Creates a gradient brush from a list of colors.

Demo Code


using System.Windows.Media;
using System.Windows;
using System.Linq;
using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Creates a gradient brush from a list of colors.
        /// </summary>
        /// <param name="colors">The colors.</param>
        /// <param name="horizontal">if set to <c>true</c> [horizontal].</param>
        /// <returns>A LinearGradientBrush.</returns>
        public static LinearGradientBrush CreateGradientBrush(IList<Color> colors, bool horizontal = true)
        {//from www  .  j  a v  a 2s  .c o  m
            var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = horizontal ? new Point(1, 0) : new Point(0, 1) };
            int n = colors.Count;
            for (int i = 0; i < n; i++)
            {
                var gs = new GradientStop(colors[i], (double)i / (n - 1));
                brush.GradientStops.Add(gs);
            }

            return brush;
        }
        /// <summary>
        /// Creates a gradient brush from the given colors.
        /// </summary>
        /// <param name="colors">
        /// The colors.
        /// </param>
        /// <returns>
        /// A LinearGradientBrush.
        /// </returns>
        public static LinearGradientBrush CreateGradientBrush(params Color[] colors)
        {
            return CreateGradientBrush(colors.ToList());
        }
}

Related Tutorials