2018/11/15

[C#] WPF Convert HSV to RGB Color

在 WPF 裡面要將物件上色,都是用
object.Fill = new SolidColorBrush(Color.FromRgb(R, G, B));
但如果介面想要用 HSV 來當作輸入參數的話,這邊有一個轉換的方法參考
色彩轉換方法 HSV2RGB(h, s, v)
object.Fill = new SolidColorBrush( HSV2RGB(h, s, v) );

輸入HSV參數(0~255)
輸出RGB (byte)給物件填滿色彩
// H:0~255, S:0~255, V:0~255
private Color HSV2RGB(float H, float S, float V)
{
    float H_Index = H / 255 * 360;
    float S_Index = S / 255;
    float V_Index = V / 255;
            
    float C = V_Index * S_Index;
    float X = C * (1 - Math.Abs(H_Index / 60 % 2 - 1));
    float m = V_Index - C;

    float R_Index, G_Index, B_Index;

    if (H_Index >= 0 && H_Index < 60)
    {
        R_Index = C;
        G_Index = X;
        B_Index = 0;
    }
    else if (H_Index >= 60 && H_Index < 120)
    {
        R_Index = X;
        G_Index = C;
        B_Index = 0;
    }
    else if (H_Index >= 120 && H_Index < 180)
    {
        R_Index = 0;
        G_Index = C;
        B_Index = X;
    }
    else if (H_Index >= 180 && H_Index < 240)
    {
        R_Index = 0;
        G_Index = X;
        B_Index = C;
    }
    else if ((H_Index >= 240 && H_Index < 300))
    {
        R_Index = X;
        G_Index = 0;
        B_Index = C;
    }
    else
    {
        R_Index = C;
        G_Index = 0;
        B_Index = X;
    }
    return Color.FromRgb((byte)((R_Index + m) * 255), (byte)((G_Index + m) * 255), (byte)((B_Index + m) * 255));
}


END

沒有留言:

張貼留言