当我将鼠标移到pictureBox1上时,如何在pictureBox 2上自动绘制点?

时间:2013-12-05 23:46:11

标签: c# winforms

private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                points.Add(new PointF(e.X * xFactor, e.Y * yFactor));
                pictureBox2.Invalidate();
                label5.Visible = true;
                label5.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
                counter += 1;
                label6.Visible = true;
                label6.Text = counter.ToString();
            }
        }

         private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        label4.Visible = true;
        label4.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
        if (panning)
        {
            movingPoint = new Point(e.Location.X - startingPoint.X,
                                    e.Location.Y - startingPoint.Y);
            pictureBox1.Invalidate();
        }
    }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            Pen p;
            p = new Pen(Brushes.Green);
            foreach (PointF pt in points)
            {
                e.Graphics.FillEllipse(Brushes.Red, pt.X, pt.Y, 3f, 3f);
            }

            for (int i = 0; i < points.Count - 1; i++)
            {
                if (points.Count > 1)
                {
                    e.Graphics.DrawLine(p, points[i].X, points[i].Y, points[i+1].X, points[i+1].Y);
                }
            }

            if (checkBox2.Checked)
            {

            }
        }

我添加了一个新的checkBox2并且在checkBox2的绘制事件中我想要检查是否我只是将鼠标移动到pictureBox1区域而不点击任何东西它会在pictureBox2上绘制一条线鼠标所在的路径移动到pictureBox1。

我移动鼠标的X像素将在此线上创建一个绿色点。

1 个答案:

答案 0 :(得分:0)

您可以使用GraphicsPath来保存鼠标所有点,这样可以比使用某些List或Array来存储点更好(并且每次绘制时都会循环绘制该图形)被提出):

GraphicsPath gp = new GraphicsPath();
Point p;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if(!label4.Visible) label4.Visible = true;
    label4.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
    if (panning) {
        if(p == Point.Empty) {
          p = e.Location;
          return;
        }
        gp.AddLine(p,e.Location);
        p = e.Location;
        pictureBox2.Invalidate();
    }
}
private void pictureBox2_Paint(object sender, PaintEventArgs e) {
   using(Pen p = new Pen(Color.Green,2f)){
        p.StartCap = p.EndCap = LineCap.Round;
        p.LineJoin = LineJoin.Round;
        e.Graphics.DrawPath(p,gp);
   }
}

请注意,在使用代码之前,您应该添加using System.Drawing.Drawing2D;