2015-02-07 48 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