using System; namespace Prism.Glass { /// /// The disc of a color picker, with hue as the angle and saturation as the distance from the center. A point is in /// screen coordinates scaled so the disc has radius 1, with x to the right and y down. Red is at the right and hue /// runs counterclockwise on screen, so yellow is at the upper right. /// public static class HueDisc { private const double TurnInRadians = 2 * Math.PI; /// /// Returns the hue at this point. The center has no hue and gives 0. /// public static double HueAt(double x, double y) { return Hues.Wrap(Math.Atan2(-y, x) / TurnInRadians); } /// /// Returns the saturation at this point, its distance from the center, held to 1 outside the disc. /// public static double SaturationAt(double x, double y) { return Math.Min(1, Math.Sqrt(x * x + y * y)); } /// /// Returns the color with the hue and saturation of this point and the value and alpha of the current color. /// The center has no hue, so it keeps the current one. /// public static Hsv Pick(double x, double y, Hsv current) { double hue = current.Hue; if (x != 0 || y != 0) { hue = HueAt(x, y); } return new Hsv(hue, SaturationAt(x, y), current.Value, current.Alpha); } /// /// Finds the point where a color sits on the disc. /// public static void PointOf(Hsv color, out double x, out double y) { double angle = color.Hue * TurnInRadians; x = color.Saturation * Math.Cos(angle); y = -color.Saturation * Math.Sin(angle); } /// /// Draws the disc into a square buffer at this value. Alpha falls from 1 to 0 across a one-pixel rim. A rim /// pixel holds the full saturation of its hue, so smoothing never blends in a darker edge. /// /// The buffer isn't diameter by diameter pixels. /// /// The diameter is less than 1, or the value isn't 0 to 1. /// public static void Fill(byte[] pixels, int diameter, double value) { Rgba.CheckBuffer(pixels, diameter, diameter); double radius = diameter / 2.0; for (int row = 0; row < diameter; row++) { double y = row + 0.5 - radius; for (int column = 0; column < diameter; column++) { double x = column + 0.5 - radius; double coverage = radius - Math.Sqrt(x * x + y * y) + 0.5; Color color = new Hsv(HueAt(x, y), SaturationAt(x / radius, y / radius), value).ToColor(); byte alpha = (byte)Math.Round(Math.Max(0, Math.Min(1, coverage)) * byte.MaxValue); Rgba.Write(pixels, row * diameter + column, Color.FromArgb(alpha, color)); } } } } }