2015-02-07 15 views
-1

如何獲取光標位置的像素顏色?我知道如何使用MousePosition獲取鼠標位置,但我無法弄清楚如何獲取該位置的像素顏色。我寫的代碼,把我都沒有結果運行鼠標位置並給出位置顏色

private void pictureBox1_MouseClick(object sender, MouseEventArgs e) 
    { 


        s= pictureBox1.PointToClient(Cursor.Position);   

        bitmap.SetPixel(s.X/40, s.Y/40, Color.Red); 

        } 
+1

好當然不是,你沒有寫代碼。使用MouseMove事件和bitmap.GetPixel() – 2015-02-07 15:24:25

回答

0

更容易使用e.Location點在Mouseclick事件的參數時:

Color c = ((Bitmap)pictureBox1.Image).GetPixel(e.X, e.Y); 

這假定確實位在PicturBoxImage,沒有畫在Control的頂部..

確保事件真的掛鉤了!

要設置點擊像素,紅說,你會得到從PB的ImageBitmap,並設置像素,然後將Bitmap回::

Bitmap bmp = (Bitmap)pictureBox1.Image; 
bmp.SetPixel(e.X, e.Y, Color.Red); 
pictureBox1.Image = bmp; 

也在MouseClick事件。

如果你想獲得更大的標記,你應該使用Graphics方法,也許是這樣的:

using (Graphics G = Graphics.FromImage(pictureBox1.Image)) 
{ 
    G.DrawEllipse(Pens.Red, e.X - 3, e.Y - 3, 6, 6); 
} 

更新:要結合獲取和設置,你可以寫:

Bitmap bmp = (Bitmap)pictureBox1.Image; 
Color target = Color.FromArgb(255, 255, 255, 255); 
Color c == bmp .GetPixel(e.X, e.Y); 
if (c == target) 
    { 
     bmp.SetPixel(e.X, e.Y, Color.Red); 
     pictureBox1.Image = bmp; 
    } 
else MessageBox.Show("Click only on white spots! You have hit " + c.ToString(), 
        "Wrong spot! "); 
+0

抱歉,但使用此Color c =((Bitmap)pictureBox1.Image).GetPixel(e.X,e.Y);在那裏我把顏色設爲ex:紅色或任何顏色我使用SetPixel給像素顏色 – lena 2015-02-07 15:44:34

+0

那麼你可以使用SetPixel在這裏相同:'((Bitmap)pictureBox1.Image).SetPixel(eX,eY,color)。紅色);' - 但是你確定你知道(或者告訴我們)你想達到什麼目的嗎?爲什麼要讀取顏色,如果你把它設置爲紅色? – TaW 2015-02-07 16:56:00

+0

我這樣做,但運行時並沒有點擊發生 – lena 2015-02-07 17:05:54