Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I asked this over on stackoverflow and it transpired it was amenable to a mathematical solution. So I am seeking clarity here, or I go night night.

//Returns the point on the line traced from start to end which
//comes nearest to 0.5, 0.5.
fpPoint closestToCentre(fpPoint start, fpPoint end);

Anyone know of quicker way than single stepping through the pixels?

Now I know how to rotate the gradient $90^o$ and can find which way easy enough, so it is now a matter of finding a line intercept and expressing this mathematically so I can solve for $x$ and $y$.

I was thinking my original line is known and : $dy_1$ = $dx_1\left(\frac{dy}{dx_1}\right) + c_1$

and the perpendicular through center is : $dy_2 = dx_2 \left( \frac{dy}{dx_2}\right) + c_2$

I don't really need trig (and to worry about negativity in certain quadrants) to rotate the grad $90^o$ do I? Night all.

share|cite|improve this question
up vote 3 down vote accepted

You want the point $(x,y)$ to be aligned with the points $(x_s,y_s)$ and $(x_e,y_e)$ and the line they make to be perpendicular to the line $(x,y)$ and $(x_o,y_o)$ make, where $x_o=y_o=.5$.

The first condition reads $$ (x-x_s)(y_e-y_s)-(y-y_s)(x_e-x_s)=0. $$ The second condition reads $$ (x-x_o)(x_e-x_s)+(y-y_o)(y_e-y_s)=0. $$ This is a Cramer system for the unknown $(x,y)$ hence $x$ and $y$ are ratios of $2\times2$ determinants depending on the parameters $(x_s,y_s,x_e,y_e,x_o,y_o)$.

Note that the common denominator of the expressions of $x$ and $y$ is $$D=(x_e-x_s)^2+(y_e-y_s)^2, $$ hence $D\ne0$ unless the points $(x_s,y_s)$ and $(x_e,y_e)$ coincide, in which case they do not define a line.

A second method is to look for $(x,y)$ as $(x,y)=(x_s,y_s)+t\cdot(x_e-x_s,y_e-y_s)$ for a given scalar $t$, and to plug this into the second condition. This yields $$ D\cdot t=(x_o-x_s)(x_e-x_s)+(y_o-y_s)(y_e-y_s), $$ hence $$ x=x_s+\frac{(x_o-x_s)(x_e-x_s)+(y_o-y_s)(y_e-y_s)}{(x_e-x_s)^2+(y_e-y_s)^2}\cdot(x_e-x_s), $$ and $$ y=y_s+\frac{(x_o-x_s)(x_e-x_s)+(y_o-y_s)(y_e-y_s)}{(x_e-x_s)^2+(y_e-y_s)^2}\cdot(y_e-y_s). $$

share|cite|improve this answer
Both work, but I like the parametric approach more... :) – J. M. Aug 22 '11 at 3:03
I like it, the second I can almost understand. For real thickies like me I needed graphics which I was denied as a newb here. – John Aug 22 '11 at 9:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.