WPF Color Generator

namespace SenenFernandez.SmartExtensionMethods
{
    using System;
    using System.Windows.Media;

    public class SmartColorGenerator
    {
        private readonly Random random;
        private static readonly object sync = new object();
        private static SmartColorGenerator instance;

        public static SmartColorGenerator Instance
        {
            get
            {
                lock (sync)
                {
                    return instance ?? (instance = new SmartColorGenerator());
                }
            }
        }

        public SmartColorGenerator(int seed = 255)
        {
            random = new Random(seed);
        }

        public SolidColorBrush GetBrush(double opacity = 1.0)
        {
            var brush = new SolidColorBrush(GetColor(opacity));
            brush.Freeze();
            return brush;
        }

        public Color GetColor(double opacity = 1.0)
        {
            int alpha = (int)
                (255*(opacity > 1.0 ? 1 : opacity < 0 ? 0 : opacity));
            var color = new Color
            {
                A = (byte) (alpha),
                R = GetNext(),
                B = GetNext(),
                G = GetNext()
            };
            return color;
        }

        private byte GetNext()
        {
            return (byte) (random.Next(127) + 128);
        }
    }
}

No hay comentarios:

Publicar un comentario