Java calculates the intersection of two line segments

Source: Internet
Author: User

1, judge the same slope not, y2-y1/x2-x1,y4-y3/x4-x3, the same no intersection, not the same as the intersection of the line to perform the second step;
2, set y=ax+b, through the slope can find the value of a, through the coordinates can find the value of B, so that two segments in the straight line two equations are obtained;

3, through two equations to find the intersection point, and then determine whether the intersection falls in the area of intersection of two segments


Code:

public static point Getcrosspoint (lseg lsega,lseg lsegb) {float x;float y;float x1=lsega.geta (). GetX (); float y1= Lsega.geta (). GetY (); float X2=lsega.getb (). GetX (); float Y2=lsega.getb (). GetY (); float X3=lsegb.geta (). GetX (); float Y3=lsegb.geta (). GetY (); float X4=lsegb.getb (). GetX (); float Y4=lsegb.getb (). GetY (); float k1=float.max_value;float K2 =float.max_value;boolean Flag1=false;boolean flag2=false;if ((x1-x2) ==0) flag1=true;if ((x3-x4) ==0) flag2=true;if (! FLAG1) k1= (y1-y2)/(X1-X2), if (!FLAG2) k2= (y3-y4)/(X3-X4), if (K1==K2) return null;if (Flag1) {if (FLAG2) return null;x=x1; if (k2==0) {y=y3;} else{y=k2* (x-x4) +y4;}} else if (Flag2) {x=x3;if (k1==0) {y=y1;} Else{y=k1* (X-X2) +y2;}} Else{if (k1==0) {y=y1;x= (y-y4)/k2+x4;} else if (k2==0) {y=y3;x= (y-y2)/k1+x2;} else{x= (k1*x2-k2*x4+y4-y2)/(K1-K2); y=k1* (x-x2) +y2;}} if (Between (x1,x2,x) &&between (y1,y2,y) &&between (x3,x4,x) &&between (y3,y4,y)) {Point point= New Point ();p oint.setx (x);p oint.sety (y); if (Point.Equals (Lsega.geta ()) | | Point.Equals (Lsega.getb ())) return NuLl;return Point;} Else{return null;}} public static Boolean between (float a,float b,float target) {if (target>=a-0.01&&target<=b+0.01| | target<=a+0.01&&target>=b-0.01) return True;elsereturn false;}}

Java calculates the intersection of two line segments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.