鼠标位置并给出位置颜色

时间:2015-02-07 15:18:04

标签: c# visual-studio-2010 mouseevent pixels

如何在光标位置获取像素的颜色?我知道如何使用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 个答案:

答案 0 :(得分:0)

e.Location事件的参数中使用Mouseclick点更容易:

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

这假设位图确实在PicturBox' Image中,而不是在Control之上绘制..

确保事件实际上已连接!

要将点击的像素设置为红色,您可以从PB Bitmap获取Image并设置像素,然后将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! ");