Created
November 12, 2017 06:16
-
-
Save bibohlog/c312166ee98da369eccae87ee73044b2 to your computer and use it in GitHub Desktop.
Get System.Windows.Media.Color from Hue / Saturation / Brightness of double values without "if" statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Get System.Windows.Media.Color from Hue / Saturation / Brightness of double values without "if" statements | |
/// </summary> | |
/// <param name="Hue">Hue in 0 to 360</param> | |
/// <param name="Saturation">Saturation in 0 to 100</param> | |
/// <param name="Brightness">Brightness(Value) in 0 to 100</param> | |
/// <returns>Color</returns> | |
Color GetColorFromHSB_(double Hue, double Saturation, double Brightness) | |
{ | |
List<double> colors = new List<double> { 0, 0, 0 }; | |
int CC = colors.Count; | |
// R, G, B | |
#region << Hue(色相) >> | |
double RelativeInDegrees = Hue / (360 / CC); | |
// 360... 2π | |
// CC... Count of RGBs = "3" basic colors | |
// - - - - - - | |
// いま、任意の相対位置 x を | |
// Rを基準に、R: 0°= 0, G: 120°= 1, B: 240°= 2 と定義する。 | |
// このとき x は色相角度(位相) degree と RGBそれぞれの角度間隔120°によって、 | |
// x = degree / 120 | |
// と表すことができる。 | |
int WholeNoPart = (int)Math.Truncate(RelativeInDegrees); | |
double FractionalPart = RelativeInDegrees % 1.0; | |
// W.N.Part...整数部 | |
// Fr.Part...小数部 | |
int StartIndex = WholeNoPart % CC; | |
int SecondIndex = (WholeNoPart + 1) % CC; | |
// - - - - - - | |
// HSBにおける色相は、任意色の相対位置 x において、 | |
// 任意色を挟む2つの基本色の組み合わせ c1, c2 で表現される。 | |
// ここで、角度の小さい方の基本色を c1 とすると、 | |
// xの整数部 w によって | |
// c1 = colors[w], c2 = colors[w+1] | |
// と表せる。 | |
double val = FractionalPart * 2; | |
double color1 = Math.Min(2 - val, 1); | |
double color2 = Math.Min(val, 1); | |
colors[StartIndex] = 255 * color1; | |
colors[SecondIndex] = 255 * color2; | |
// - - - - - - | |
// c1とc2の中間において両者は最大値をとる。 | |
// 任意色の位置 x が遠くなるほど値が相対的に小さくなる。 | |
#endregion | |
#region << Saturation(彩度) >> | |
double satAs0to1 = Saturation / 100.0; | |
colors = colors.Select(item => item += (255 - item) * (1.0 - satAs0to1)).ToList(); | |
#endregion | |
#region << Brightness / Value (輝度) >> | |
double brightAs0to1 = Brightness / 100.0; | |
colors = colors.Select(item => item *= brightAs0to1).ToList(); | |
#endregion | |
var col = Color.FromArgb(255, (byte)colors[0], (byte)colors[1], (byte)colors[2]); | |
return col; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment