BBB
BBB

Reputation: 615

All points on Line

If I draw a line from let's say: (2,3) to (42,28), how can I get all points on the line in a Point list? I tried using the slope, but I can't seem to get the hang of it. To be clear: I would like all the pixels that the line covers. So I can make the line 'clickable'.

Upvotes: 1

Views: 4066

Answers (2)

nanda
nanda

Reputation: 804

You can use the formula (x-x1)/(x1-x2) = (y-y1)/(y1-y2). And you know the points with x values ranging from 2 to 42 are on the line and their associated y values have to be found. If any of the resulting y value is not an integer then it should be approximated rightly. And if two consecutive y values differ by more than 1 then the missing y values should be mapped to the last x value.

Here is the pseudo code (tried to capture the crux of the algorithm)

prevY = y1

for(i=x1+1;i<=x2;++i)
{

  y = computeY(i);

  if(diff(y,prevY)>1) dump_points(prevY,y,i);

  prevY = y;

  dump_point(i,y);

}

dump_points(prevY,y2,x2);

I am probably not covering all the cases here (esp. not the corner ones). But the idea is that for one value of x there would could be many values of y and vice versa depending on the slope of the line. The algorithm should consider this and generate all the points.

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

This is a math question. The equation of a line is:

y = mx + c

So you need to figure out the gradient (m) and the intercept (c) and then plug in values for x to get values for y.

But what do you mean by "all the points on a line"? There is an infinite number of points if x and y are real numbers.

Upvotes: 3

Related Questions