Drawing programs often need to pick, Rect, RGN and other shapes, say that only Simple call PtinRect or PTINRGN function can return to whether the user clicks the graphic to make pick up, the straight line is a particularly specifically, if It is necessary to ask the straight line itself (that is, click on the straight line) is not difficult for the user. After all, the width of a pixel is not easy to master. At this time, it can be used to calculate the distance between the point to the straight line. If the click line is straight line in one can be allowed to pick up the straight line, as shown in the figure:
In the figure, click P (X, Y), and determine whether the line (P1, P2) is the distance P to the straight line (P1, P2) of the clicks. If the linear equation AX BY C = 0, then the points (x, y) to the linear distance are D = FABS (AX BY C) / SQRT (A * A B * B).
It is known that two points (P1, P2) on the line (P1, P2) are known, and the linear equation is (Y1-Y2) * x (x2-x1) * Y X1 * Y2-x2 * Y1 = 0.
The routine practice is like this, but the complex formula makes our procedure not to become more complicated, it is difficult to read.
We move the above line and point of the coordinate system, and the complex problem will become a lot of simple, as shown: also makes the transformation before calculating:
X1- = x2; Y1- = Y2; X- = x2; y- = Y2; x2 = 0; Y2 = 0;
In this way, the linear equation becomes Y1X-X1Y = 0, and the straight line distance formula also changes to D = Fabs (Y1 * X-x1 * Y) / SQRT (Y1 * Y1 X1 * x1), is more simple?
Is it? not yet! If this is determined, if it is finished, click on the extension line in the straight line, it will also be determined! So it is necessary to determine if it is not a click in RECT that contains the straight line, the pick is invalid.
The method is encapsulated into a function as follows:
Bool isselline (cpoint p / * mouse click * /, cpoint p1, cpoint p2 / * two endpoints * /)
{
// Return False if you click in the area
IF (! (* x1 <= x1: x2) -5, (Y1 <= Y2? Y1: Y2) -5, (x1> x2? x1: x2) 5, (Y1> Y2 ? Y1: Y2) 5), p)) Return False;
// Coordinate transformation
P1.x- = p2.x; p1.y- = p2.y; p.x- = p2.x; p.y- = p2.y; p2.x = 0; p2.y = 0;
// Calculate the distance
Double D = FABS (Y1 * P.x-x1 * p.y) / SQRT (Y1 * Y1 X1 * X1);
IF (D <5) return true; // error value can also be passed through function parameters.
Return False;
}
If there is no MFC support, it can also be defined as the following format:
Bool isselline (int X, int y / * mouse click * /, int X1, int y1, int x2, int y2 / * two endpoints * /)
Ok, it is best to make a sentence: Don't forget to include