Home > Mobile >  C# - Better ways to sort a list of colors
C# - Better ways to sort a list of colors

Time:06-04

So before someone calls this post a duplicate, let me explain. I'm trying to find more optimized sorting algorithms to organize a list of colors based on a list of hex values. I'm currently sorting colors based on hue. This is fine, but when there are a bunch of colors, it seems to generate allot of noise.

enter image description here

I'm currently trying to find C# ways of sorting a giant list of random hex values. I have referenced this enter image description here or enter image description here

CodePudding user response:

Upd: I made an adjustment to match the hue orientation more like the example.

I have recreated the style form your example, you just need to sort the array using this comparer:

class ColorRampComparer : IComparer<Color>
{
    public int Compare(Color a, Color b)
    {
        var c1 = Step(a);
        var c2 = Step(b);

        return ((IComparable)c1).CompareTo(c2);
    }

    private Tuple<int, int, int> Step(Color color, int repetitions = 8)
    {
        int lum = (int)Math.Sqrt(.241 * color.R   .691 * color.G   .068 * color.B);

        float hue = 1 - Rotate(color.GetHue(), 90) / 360;
        float lightness = color.GetBrightness();

        int h2 = (int)(hue * repetitions);
        int v2 = (int)(lightness * repetitions);

        // To achieve second style uncomment this condition
        //if ((h2 % 2) == 0)
        //    v2 = repetitions - v2;
        //else
        //    lum = repetitions - lum;

        return Tuple.Create(h2, lum, v2);
    }

    private float Rotate(float angle, float degrees)
    {
        angle = (angle   degrees) % 360;
        if (angle < 0) angle  = 360;
        return angle;
    }
}

Results are the next:

First example

And if you uncomment the fragment in Step function, then it will look like this: Second example

To sort an array or enumerable use Sort method:

colors.Sort(new ColorRampComparer());
  • Related