如何在鼠标点击事件中更改像素的颜色?

时间:2011-06-17 08:09:43

标签: c# .net graphics mouseevent

当在运行时(即加载图像时)在图片框上的某个点上单击鼠标时,它应该改变该位置处像素的颜色。我有这段代码显示错误。

    private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        Bitmap bm=new Bitmap(1,1);
        bm.SetPixel(0,0,Color.Red);
        e.Graphics.DrawImageUnscaled(bm,e.X,e.Y);
    }

错误是'System.Windows.Forms.MouseEventArgs'不包含'Graphics'的定义,并且没有扩展方法'Graphics'可以找到接受类型'System.Windows.Forms.MouseEventArgs'的第一个参数'(你错过了使用指令或程序集引用吗?)

即使我包含了system.drawing,也显示此错误。

1 个答案:

答案 0 :(得分:3)

尝试更改图片框中的图片,而不是尝试重绘图片,因为MouseEventArgs不包含任何图形属性。

示例:

int radius = 3; //Set the number of pixel you wan to use here
 //Calculate the numbers based on radius
int x0 = Math.Max(e.X-(radius/2),0),
    y0 = Math.Max(e.Y-(radius/2),0),
    x1 = Math.Min(e.X+(radius/2),pictureBox1.Width),
    y1 = Math.Min(e.Y+(radius/2),pictureBox1.Height);
Bitmap bm = pictureBox1.Image as BitMap; //Get the bitmap (assuming it is stored that way)
for (int ix = x0; ix < x1; ix++)
{
   for (int iy = y0; iy < y1; iy++)
   {
    bm.SetPixel(ix,iy, Color.Read); //Change the pixel color, maybe should be relative to bitmap
   }
}
pictureBox1.Refresh(); //Force refresh

编辑:根据填充半径选择了多个像素