objective c Distance from point to line and intersection with vertical foot
- 2021-12-11 19:14:18
- OfStack
Problem description
The distance from a point to a line or segment
Realization thought
Assuming that there are 1 point coordinates P (x0, y0), 1 line segment AB, A coordinates (x1, y1) and B coordinates (x2, y2), find the distance d from P point to AB line segment or straight line, and the vertical foot C (x, y) of P point on straight line.
This requires a review of mathematics knowledge in high school.
Firstly, the coordinates of A and B need to be transformed into the general formula Ax+By+C = 0, so the process will not be deduced.
Parameter calculation:
A=y2-y1;
B=x1-x2;
C=x2*y1-x1*y2;
1. Distance formula from point to line:
d= ( Ax0 + By0 + C ) / sqrt ( A*A + B*B );
2. Calculation formula of C (x, y) of vertical foot:
x = ( B*B*x0 - A*B*y0 - A*C ) / ( A*A + B*B );
y = (-A*B*x0+A*A*y0-B*C)/(A*A + B*B);
Implementation of the program:
// Vertical foot intersection
-(CGPoint)pedalPoint: (CGPoint)p1 : (CGPoint )p2: (CGPoint)x0{
float A=p2.y-p1.y;
float B=p1.x-p2.x;
float C=p2.x*p1.y-p1.x*p2.y;
float x=(B*B*x0.x-A*B*x0.y-A*C)/(A*A+B*B);
float y=(-A*B*x0.x+A*A*x0.y-B*C)/(A*A+B*B);
// Point-to-line distance
float d=(A*x0.x+B*x0.y+C)/sqrt(A*A+B*B);
CGPoint ptCross=ccp(x,y);
NSLog(@ " d======%f " ,d);
NSLog(@ " A=======%f,B=======%f,C=======%f " ,A,B,C);
NSLog(@ "Hanging your feet ======x=%f,y=%f " ,x,y);
return ptCross;
}
Summarize