Lets say I have my first Point struct:
Point start = new Point(1, 9);
and my second:
Point end = new Point(4, 9);
I want to get all the points between the start and end. So for example I would want 2,9 and 3,9 in an array. Does .NET have something built in for this?
When given the end points of a line segment, you can find out its midpoint by using the midpoint formula. As the name might have already suggested, midpoint is basically the halfway between two end points. All you need to do is dividing the sum of x-values and the sum of y-values by 2.
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.
To find points on the line y = mx + b, choose x and solve the equation for y, or. choose y and solve for x.
This is what I ended up doing. As @Cody Gray mentioned in his comment, there are infinite points on a line. So you need to specify how many points you are looking to retrieve.
My Line class:
public class Line {
public Point p1, p2;
public Line(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
public Point[] getPoints(int quantity) {
var points = new Point[quantity];
int ydiff = p2.Y - p1.Y, xdiff = p2.X - p1.X;
double slope = (double)(p2.Y - p1.Y) / (p2.X - p1.X);
double x, y;
--quantity;
for (double i = 0; i < quantity; i++) {
y = slope == 0 ? 0 : ydiff * (i / quantity);
x = slope == 0 ? xdiff * (i / quantity) : y / slope;
points[(int)i] = new Point((int)Math.Round(x) + p1.X, (int)Math.Round(y) + p1.Y);
}
points[quantity] = p2;
return points;
}
}
Usage:
var line = new Line(new Point(10, 15), new Point(297, 316));
var points = line.getPoints(20);
That will return a Point array of 20 Points evenly spaced between the two endpoints (inclusive). Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With