通过单击交点将两条线拖动在一起

本文关键字:两条线 拖动 在一起 单击 | 更新日期: 2023-09-27 18:19:01

我有一个包含两个图片框(_pic1, _pic2)的mainPicture框。我也可以拖动_pic1和_pic2。但是我想当我在两个图片框的交叉处下鼠标时,我可以将两条线拖到一起。所以我应该得到交点位置。

_pic2.MouseUp += new MouseEventHandler(_pic1_MouseUp);
 _pic2.MouseDown += new MouseEventHandler(_pic1_MouseDown);
 Point p = new Point();
 bool interSection;
        private void _pic1_MouseDown(object sender, MouseEventArgs e)
         {
        p = e.Location;
        dragging = true;
        dragPoint = new Point(e.X, e.Y);
        this.Cursor = Cursors.SizeAll;

        Rectangle p1 = this._pic1.ClientRectangle;
        p1.Offset(this._pic1.Location);
        Rectangle p2 = this._pic2.ClientRectangle;
        p2.Offset(this._pic2.Location);

            //bool z = p1.Contains(p)      it returns false
            //bool zz = p2.Contains(p)      it returns false too

        if (p1.Contains(p) && p2.Contains(p))
        {
            interSection = true;
        }
           }
        private void _pic_MouseMove(object sender, MouseEventArgs e)
        {
        if (interSection)
        {
         //drag two lines together
            _pic1.Location = new Point(_pic1.Location.X + e.X - dragPoint.X, _pic1.Location.Y + e.Y - dragPoint.Y);
            _pic2.Location = new Point(_pic2.Location.X + e.X - dragPoint.X, _pic2.Location.Y + e.Y - dragPoint.Y);
            return; 
        }
        if (dragging)
        {
            _pic_1.Location = new Point(_pic1.Location.X + e.X - dragPoint.X, _pic1.Location.Y + e.Y - dragPoint.Y);
        }
    }
           private void _pic1_MouseUp(object sender, MouseEventArgs e)
           {
        dragging = false;
        this.Cursor = Cursors.Default;
            }
          private void _pic2_MouseMove(object sender, MouseEventArgs e)
            {
        if (dragging)
        {
            _pic2.Location = new Point(_pic2.Location.X + e.X - dragPoint.X, _pic2.Location.Y + e.Y - dragPoint.Y);
        }
    }

图片:

     http://tinypic.com/view.php?pic=ix8bab&s=8

通过单击交点将两条线拖动在一起

你可以像这样测试两个矩形的交集:

if (_pic1.Bounds.IntersectsWith(_pic2.Bounds) ) // do stuff

你可以得到这样的交集:

Rectangle R = _pic1.Bounds;
R.Intersect(_pic2.Bounds);

现在你可以再测试一次:

if (R != Rectangle.Empty)

或查找中心:

Point center = new Point(R.X + R.Width / 2, R.Y + R.Height / 2);

或者测试鼠标是否被点击在交点上:

if (R.Contains(e.Location) // ..