C# Code Snippets

Project a 2D Point on a Line

Visual C# Kicks

Perpendicularly project a 2D point onto a 2D line.

Platform: .NET Framework 2.0

private Point Project(Point line1, Point line2, Point toProject)
{
    double m = (double)(line2.Y - line1.Y) / (line2.X - line1.X);
    double b = (double)line1.Y - (m * line1.X);

    double x = (m * toProject.Y + toProject.X - m * b) / (m * m + 1);
    double y = (m * m * toProject.Y + m * toProject.X + b) / (m * m + 1);

    return new Point((int)x, (int)y);
}

 

Back to C# Code Snippet List