Search code examples
c#geometryline

Obtaining the point at a certain percentage along a line segment


I have a method that returns the mid point of a line segment as defined by two points;

public static PointF GetMidPoint(PointF p1, PointF p2)
{
    return new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
}

Which works exactly as expected.

However, I now need to find an arbitrary percentage along the segment (say, 35%), which in principle should(?) be as easy as;

public static PointF GetArbitaryPoint(PointF p1, PointF p2, double percentage)
{
    return new PointF((p1.X + p2.X) / percentage, (p1.Y + p2.Y) / percentage);
}

But that doesn't seem to be the case, I think it's a c# issue - as soon as you introduce a decimal point (whether it be a Point or a PointF) it throws it's toys out of the pram and returns bizarre results.

So I suppose the question is how would I modify the above to get it do what I need?

Thanks in advance.


Solution

  • You are using the wrong formula.

    The weighted middle between two points is p1 + (p2-p1) * percentage, which just happens to work out for 0.5 as p1 + (p2-p1)*0.5 = (p1 + p2) * 0.5