简体   繁体   中英

drag two lines together by clicking on intersection point

I have a mainPicture box that contains Two picture boxes (_pic1 , _pic2) . I can drag _pic1 and drag _pic2 too. But I want to when I do mouse down on intersection of two picture boxes, I could drag two lines together . So I should get intersection position . by below code I could not.

_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);
        }
    }

image :

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

You can test two Rectangles for Intersection like this:

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

And you can get the intersection like this:

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

Now you can test it again:

if (R != Rectangle.Empty)

Or find the Center:

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

Or test whether the Mouse was clicked on the intersection:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM