16進数6桁文字列からカラーを取得

16進数6桁文字列からカラーを取得

前回のカラーコードを16進数表示するに続き、今回はその逆の16進数文字列からカラー値を求めるサンプルを紹介。

このサンプルでは以下の処理を行う。

  1. テキストボックスに16進数6桁のRGBの値を指定
  2. ボタンをクリックで、ボタンの背景色を指定カラーに変更
  3. ついでにボタンの文字列も色を反転

GUIデザインでは、Formにbutton2という名前のボタンと、textBox1という名前のテキストボックスを貼り付ける。


ソースコードは以下の通り。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
	public partial class Form2 : Form
	{
		public Form2()
		{
			InitializeComponent();
		}

		private void button2_Click(object sender, EventArgs e)
		{
			// RGBカラーコード(16進数6桁文字列)を赤、緑、青に振り分け
			int r = Convert.ToInt32(textBox1.Text.Substring(0, 2), 16);
			int g = Convert.ToInt32(textBox1.Text.Substring(2, 2), 16);
			int b = Convert.ToInt32(textBox1.Text.Substring(4, 2), 16);

			// RGBの値からColorの値を求める
			Color col = Color.FromArgb(r, g, b);

			// ボタン背景色へ反映
			button2.BackColor = col;

			// ボタンの文字を反転カラーに変更(RGBをそれぞれ反転)
			button2.ForeColor = Color.FromArgb(0xFF - col.R,
			0xFF - col.G,
			0xFF - col.B);
		}
	}
}

実行後、テキストボックスにRGB値(000000~FFFFFF)を指定し、ボタン押下すると、ボタンの色が変わる。

Tagged

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


*