[CSharpTips]C# 判断一个点是否在线段上

C# 判断一个点是否在线段上

using System;
using System.Collections.Generic;
using System.Windows;

namespace PointInLineTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Point> points = new List<Point>();
            points.Add(new Point(97.513, 5.076));
            points.Add(new Point(103.589, 11.153));
            points.Add(new Point(131.885, 39.449));
            var result = GetPointIsInLine(points[1], points[0], points[2], 0.001);
            Console.WriteLine(result);
            Console.ReadLine();
        }
        /// <summary>
        /// 判断点是否在线段上
        /// </summary>
        /// <param name="pf">判断点</param>
        /// <param name="p1">线段起点</param>
        /// <param name="p2">线段终点</param>
        /// <param name="range">判断的的误差,不需要误差则赋值0</param>
        /// <returns></returns>
        public static bool GetPointIsInLine(Point pf, Point p1, Point p2, double range)
        {
            //点在线段首尾两端之外则return false
            double cross = (p2.X - p1.X) * (pf.X - p1.X) + (p2.Y - p1.Y) * (pf.Y - p1.Y);
            if (cross <= 0) return false;
            double d2 = (p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y);
            if (cross >= d2) return false;

            double r = cross / d2;
            double px = p1.X + (p2.X - p1.X) * r;
            double py = p1.Y + (p2.Y - p1.Y) * r;

            //判断距离是否小于误差
            return Math.Sqrt((pf.X - px) * (pf.X - px) + (py - pf.Y) * (py - pf.Y)) <= range;
        }
    }
}

运行结果

 

posted @ 2022-09-23 13:31  xiaoshuye  阅读(630)  评论(0编辑  收藏  举报