如何判断一条线是否与

如何判断一条线是否与

本文介绍了如何判断一条线是否与 C# 中的多边形相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此非常相似的问题:

I have a question very similar to this:

在 C# 中如何知道一条线是否与平面相交?

我正在寻找一种方法(在 C# 中)可以判断一条线是否与任意多边形相交.

I am searching for a method (in C#) that tells if a line is intersecting an arbitrary polygon.

我认为 Chris Marasti-Georg 的算法 很有帮助,但缺少最重要的方法,即行线交点.

I think the algorithm by Chris Marasti-Georg was very helpful, but missing the most important method, i.e. line to line intersection.

有谁知道完成 Chris Marasti-Georg 代码的线交叉方法或有类似的方法吗?

Does anyone know of a line intersection method to complete Chris Marasti-Georg's code or have anything similar?

C# 中是否有内置代码?

Is there a built-in code for this in C#?

此方法用于通过禁用区域功能增强的 Bing 地图算法.生成的路径不得通过禁止区域(任意多边形).

This method is for use with the Bing Maps algorithm enhanced with a forbidden area feature. The resulting path must not pass through the forbidden area (the arbitrary polygon).

推荐答案

.NET 框架中没有用于边缘检测的内置代码.

There is no builtin code for edge detection built into the .NET framework.

这里的代码(移植到 C#)可以满足您的需求(实际算法可以在 Google 群组的 comp.graphics.algorithms 中找到):

Here's code (ported to C#) that does what you need (the actual algorithm is found at comp.graphics.algorithms on Google groups) :

public static PointF FindLineIntersection(PointF start1, PointF end1, PointF start2, PointF end2)
{
    float denom = ((end1.X - start1.X) * (end2.Y - start2.Y)) - ((end1.Y - start1.Y) * (end2.X - start2.X));

    //  AB & CD are parallel
    if (denom == 0)
        return PointF.Empty;

    float numer = ((start1.Y - start2.Y) * (end2.X - start2.X)) - ((start1.X - start2.X) * (end2.Y - start2.Y));

    float r = numer / denom;

    float numer2 = ((start1.Y - start2.Y) * (end1.X - start1.X)) - ((start1.X - start2.X) * (end1.Y - start1.Y));

    float s = numer2 / denom;

    if ((r < 0 || r > 1) || (s < 0 || s > 1))
        return PointF.Empty;

    // Find intersection point
    PointF result = new PointF();
    result.X = start1.X + (r * (end1.X - start1.X));
    result.Y = start1.Y + (r * (end1.Y - start1.Y));

    return result;
 }

这篇关于如何判断一条线是否与 C# 中的多边形相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:38