今天要用到一个颜色渐变的算法,网上看了很多,觉得都太繁琐,索性自己写一个。话不多说,直接上代码!
**这是用来获取某一颜色段的分度集合**
/// <summary>
/// 获得某一颜色区间的颜色集合
/// </summary>
/// <param name="sourceColor">起始颜色</param>
/// <param name="destColor">终止颜色</param>
/// <param name="count">分度数</param>
/// <returns>返回颜色集合</returns>
public static List<Color> GetSingleColorList(Color srcColor, Color desColor, int count)
{
List<Color> colorFactorList = new List<Color>();
int redSpan = desColor.R - srcColor.R;
int greenSpan = desColor.G - srcColor.G;
int blueSpan = desColor.B - srcColor.B;
for (int i = 0; i < count; i++)
{
Color color = Color.FromArgb(
srcColor.R + (int)((double)i / count * redSpan),
srcColor.G + (int)((double)i / count * greenSpan),
srcColor.B + (int)((double)i / count * blueSpan)
);
colorFactorList.Add(color);
}
return colorFactorList;
}
**这里就是将红到紫之间的颜色分为5个区间,利用上面的算法拼接5个区间的分度值,就得到全彩颜色集合**
/// <summary>
/// 获取从红到紫的颜色段的颜色集合
/// </summary>
/// <param name="totalCount">分度数</param>
/// <param name="redToPurple">是否从红到紫色渐变</param>
/// <returns>返回颜色集合</returns>
public static List<Color> GetFullColorList(int totalCount, bool redToPurple = true)
{
List<Color> colorList = new List<Color>();
if (totalCount > 0)
{
if (redToPurple)
{
colorList.AddRange(GetSingleColorList(Color.Red, Color.Yellow, totalCount / 5 + (totalCount % 5 > 0 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Yellow, Color.Lime, totalCount / 5 + (totalCount % 5 > 1 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Lime, Color.Cyan, totalCount / 5 + (totalCount % 5 > 2 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Cyan, Color.Blue, totalCount / 5 + (totalCount % 5 > 3 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Blue, Color.Magenta, totalCount / 5 + (totalCount % 5 > 4 ? 1 : 0)));
}
else
{
colorList.AddRange(GetSingleColorList(Color.Magenta, Color.Blue, totalCount / 5 + (totalCount % 5 > 0 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Blue, Color.Cyan, totalCount / 5 + (totalCount % 5 > 1 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Cyan, Color.Lime, totalCount / 5 + (totalCount % 5 > 2 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Lime, Color.Yellow, totalCount / 5 + (totalCount % 5 > 3 ? 1 : 0)));
colorList.AddRange(GetSingleColorList(Color.Yellow, Color.Red, totalCount / 5 + (totalCount % 5 > 4 ? 1 : 0)));
}
}
return colorList;
}