目次

Colorオブジェクトから HSB値(色相 彩度 明度)を取得する - ColorからHSBへの変換 - C#

Colorオブジェクトから 色相、彩度、明度(明るさ)の値を取得するコードを紹介します。

UI

下図のUIを作成します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ColorToHSB
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      int R = (int)numericUpDown_R.Value;
      int G = (int)numericUpDown_G.Value;
      int B = (int)numericUpDown_B.Value;

      Color color = Color.FromArgb(R, G, B);
      float hue = color.GetHue();
      float saturation = color.GetSaturation();
      float brightness = color.GetBrightness();

      textBox_Hue.Text = string.Format("{0:0.###}", hue);
      textBox_Saturation.Text = string.Format("{0:0.###}", saturation);
      textBox_Brightness.Text = string.Format("{0:0.###}", brightness);
            
      panel1.BackColor = color;
    }
  }
}

解説

  int R = (int)numericUpDown_R.Value;
  int G = (int)numericUpDown_G.Value;
  int B = (int)numericUpDown_B.Value;
にて、スピンボックスからR,G,B成分の値を取得します。

  Color color = Color.FromArgb(R, G, B);
にて、RGB成分の値からColorオブジェクトを作成します。詳しくはこちらの記事を参照してください。

  float hue = color.GetHue();
  float saturation = color.GetSaturation();
  float brightness = color.GetBrightness();
ColorオブジェクトのGetHue()メソッドを用いて色相を、GetnSaturation()メソッドを用いて彩度を、GetBrightness()メソッドを呼び出して明度を取得します。

  textBox_Hue.Text = string.Format("{0:0.###}", hue);
  textBox_Saturation.Text = string.Format("{0:0.###}", saturation);
  textBox_Brightness.Text = string.Format("{0:0.###}", brightness);
            
  panel1.BackColor = color;
にて、取得した色相、彩度、明度の値をテキストボックスに表示します。また、パネルの背景色を与えたR,G,B値の色にします。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


スピンボックスに何も入力しない状態で[Create]ボタンを押します。黒色の色相、彩度、明度の値が下部のテキストボックスに表示され、パネルの背景色が黒に変わります。


スピンボックスの値を変更し[Create]ボタンを押します。スピンボックスに入力した値のR,G,B値の色の色相、彩度、明度の値が下部のテキストボックスに表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2017-09-11
作成日: 2012-12-19
iPentec all rights reserverd.