首页 > 解决方案 > C#在半径内的网格上获取附近的点

问题描述

我有一个具有 X 和 Y 坐标的网格。在这个网格上,我有一个起点,我想获得一定半径内的所有附近单元格。

我制作了以下函数,该函数在每个方向上 +1 并返回点。

    public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance)
    {
        var nearbySpots = new List<Point>();
        int StartDistance = 1;

        while (StartDistance < Distance)
        {
            nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y - StartDistance)));
            nearbySpots.Add(new Point((short)(fromLocation.X + StartDistance), fromLocation.Y));
            nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y + StartDistance)));
            nearbySpots.Add(new Point((short)(fromLocation.X - StartDistance), fromLocation.Y));

            StartDistance++;
        }

        return nearbySpots;
    }

这将从我的起点返回直线上的所有点。但是我也想抓住中间点。

这是我目前得到的(对不起,糟糕的形象)

我返回的点的图像

但是,我希望能够输入 2 的距离并在起始位置周围获得完整的正方形。

我想要什么与诊断完全一致

所以我问有没有什么简单的方法可以让我得到对角线,而不仅仅是从起点开始的直线?

标签: c#gridpoints

解决方案


由于它是一个矩形,因此您可以使用一种非常简单的方法。假设这Distance总是积极的:

public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance) {

    var nearbySpots = new List<Point>();

    for (int i = -Distance; i <= Distance; ++i)
        for (int j = -Distance; j <= Distance; ++j)
            nearbySpots.Add(new Point(fromLocation.X + j, fromLocation.Y + i));

    return nearbySpots;

}

这个想法是从左上角开始,逐行添加矩形中的每个点,到右下角结束。


推荐阅读