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

时间:2014-08-22 09:45:52

标签: c#

我有一个mainPicture框,其中包含两个图片框(_pic1,_pic2)。 我也可以拖动_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

1 个答案:

答案 0 :(得分:0)

您可以像这样测试两个交叉矩形:

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) // ..