在位图顶部拖动图形对象

时间:2011-02-02 09:28:10

标签: c# picturebox system.drawing imaging drawellipse

我试图在mousemove事件上拖动图片框周围的形状,但我正在努力让它顺利移动。图片框中加载了一个图像作为背景,我希望图形对象在单击并拖动鼠标时在图像顶部拖动一个圆圈。

每次鼠标移动并重新装入图片框时,我都会通过创建原始图像的克隆来实现它,但似乎它们必须是实现此目的的更好方法。

每次添加任何图形时都不会重新加载原始位图,从而创建一个更像绘画应用程序的轨迹。

如何在不重新加载整个图像的情况下清除以前的图纸?任何帮助表示赞赏。

private void picCanvas_MouseMove(object sender, MouseEventArgs e)
{
    if (_drag)
    {
        picCanvas.Image = (Bitmap)_original.Clone();
        Graphics g = Graphics.FromImage((Bitmap)picCanvas.Image);
        g.DrawEllipse(_whitePen, e.X, e.Y, 10, 10);
        picCanvas.Invalidate();
    }
}

private void picCanvas_MouseDown(object sender, MouseEventArgs e)
{
    _drag = true;
}

private void picCanvas_MouseUp(object sender, MouseEventArgs e)
{
    _drag = false;
}

3 个答案:

答案 0 :(得分:3)

检查此样本是否更简单

//Load Image
Bitmap TestImage = new Bitmap(FileName);
//Create Graphics Object
Graphics g = Graphics.FromImage(TestImage);                   
g.DrawEllipse(new Pen(Color.Red), i, j,0.5F, 0.5F);
//View Your Results
pictureBox1.Image = TestImage;

答案 1 :(得分:0)

要以最佳方式解决问题,请使用picCanvas.Paint事件。 在mousemove事件中设置位置,并使用该位置在绘制事件中绘制。

    Point pos = Point.Empty;// or your initial position

    private void picCanvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (_drag)
        {
            pos = e.Location;
        }
    }
    private void picCanvas_Paint(object sender, PaintEventArgs e)
    {
        if (_drag)
        {
            Graphics g = e.Graphics;//The event handler sends us the graphics object to use for painting
            g.DrawEllipse(_whitePen, pos.X, pos.Y, 10, 10); 
        }
    }

您应该将Paint事件添加到Control并将图像设置为formload或某些初始化函数。

picCanvas.Image = (Bitmap)_original.Clone(); 

答案 2 :(得分:0)

使用Honibis的上述答案,我最终得到了这个。

加载图像并使图片无效以进行刷新

picCanvas.Image = image;
picCanvas.Invalidate()

然后在paint事件中

private void picCanvas_Paint(object sender, PaintEventArgs e)
{
  if (_drag)         
  {
    using (Pen pen = new Pen(Color.White, 2))
    {
      e.Graphics.DrawEllipse(pen, pos.X, pos.Y, 10, 10);
    }
  }
}