well of course if your line is vertical the slope is infinite and you cannot "shorten" it the way you're trying to do... You can check that just like jacek suggests.
mathematically speaking a vector is a "difference" of two points or a "movement" to go from a point to another (purely graphical explanation here. my math teacher would strangle me if he were to read this
)
code-wise, a vector and a point are exactly the same thing : a bunch of coordinates. The only difference is the way you use them.
proceed like this :
- compute the vector that directs your line by substracting the two extremities
- normalize it (i.e divide it by its length)
- multiply it by the desired length (here 20 pix)
- add it back to the starting point of your line to obtain the new interpolated point on the same line
vec /= sqrt(pow(vec.x(), 2), pow(vec.y(), 2));
vec *= 20;
QPoint interpolated
= start
+ vec.
toPoint();
QPointF vec = end - start;
vec /= sqrt(pow(vec.x(), 2), pow(vec.y(), 2));
vec *= 20;
QPoint interpolated = start + vec.toPoint();
To copy to clipboard, switch view to plain text mode
The use of a QPointF here is only *recommended* for more precision. A less accurate but faster version would be :
vec /= vec.manhattanLength();
vec *= 20;
QPoint interpolated
= start
+ vec;
QPoint vec = end - start;
vec /= vec.manhattanLength();
vec *= 20;
QPoint interpolated = start + vec;
To copy to clipboard, switch view to plain text mode
edit : the sample code uses Qt but the method described here is not dependent on Qt (I'd have written this in plain C++ but I didn't feel like declaring my own Point class before
)
Bookmarks