Get Gradient For Two Colors - CSharp System.Drawing

CSharp examples for System.Drawing:Color

Description

Get Gradient For Two Colors

Demo Code


using System.Drawing;
using System.Collections.Generic;
using System;// w  w w.  ja  v  a2s  . co m

public class Main{
        private static Color GetGradientForTwoColors(double position,
            Color start, Color end)
        {
            if (position < 0 || position > 1)
                throw new ArgumentException(
                    "Position should be between 0 and 1");

            double negativePosition = 1.0 - position;

            double alpha = Math.Min(start.A, end.A) + Math.Abs(start.A - end.A) *
                           (start.A > end.A ? negativePosition : position);
            double red = Math.Min(start.R, end.R) + Math.Abs(start.R - end.R) *
                         (start.R > end.R ? negativePosition : position);
            double green = Math.Min(start.G, end.G) + Math.Abs(start.G - end.G) *
                           (start.G > end.G ? negativePosition : position);
            double blue = Math.Min(start.B, end.B) + Math.Abs(start.B - end.B) *
                          (start.B > end.B ? negativePosition : position);

            return Color.FromArgb((int)alpha, (int)red, (int)green, (int)blue);
        }
}

Related Tutorials