- 顯示 Window Form 內滑鼠位置座標。
- 顯示圖片內之滑鼠座標下像素的 RGB 值。
Step1. 檔案 → 新增專案 → Windows Form 應用程式 → 拉物件 Form1.cs[設計] → 撰寫 Form1.cs
Step2. 將圖片放至「專案/bin/Debug」目錄內。
Step3. Windows Form 拉入需要工具:
- pictureBox × 1
- button × 1
- textBox × 5
- Label × 5
- openFileDialog × 1
Step4. 於 Form1.cs[設計] → pictureBox1 屬性 → sizeMode 改為 StretchImage。
Step5. Coding Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MouseGraphic { public partial class Form1 : Form { //Bitmap imgone = new Bitmap("lena.png"); Bitmap imgone; Color colorPixel; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { imgone = new Bitmap("lena.png"); pictureBox1.Image = imgone; } private void button1_Click(object sender, EventArgs e) { OpenFileDialog OpenImage = new OpenFileDialog(); if (OpenImage.ShowDialog() == DialogResult.OK) { imgone = new Bitmap(OpenImage.FileName); pictureBox1.Image = imgone; } } // 自建一個 Mouse Move Listener private void imgone_MouseMove(object sender, MouseEventArgs e) { //顯示滑鼠座標 textBox1.Text = e.X.ToString(); textBox2.Text = e.Y.ToString(); // 當滑鼠進入圖片內時才捉 RGB 值 if ((e.X < imgone.Width) && (e.Y < imgone.Height)) { //取得pixel的RGB值 colorPixel = imgone.GetPixel(e.X, e.Y); textBox3.Text = colorPixel.R.ToString(); textBox4.Text = colorPixel.G.ToString(); textBox5.Text = colorPixel.B.ToString(); } } } }
Step6.
修改 Form1.Designer.cs → 展開全部程式 → 找到「// pictureBox1」分類 →於其下方加入:
// // pictureBox1 // this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.imgone_MouseMove);
請問用WPF的話要怎麼取得RGB值
回覆刪除