可以说,我有我的第一点的结构:如何获取两个Point对象之间的所有点?
Point start = new Point(1, 9);
和我的第二个:
Point end = new Point(4, 9);
我想所有的起点和终点之间的点。因此,例如,我会想在数组中的2,9和3,9。 .NET有内置的东西吗?
可以说,我有我的第一点的结构:如何获取两个Point对象之间的所有点?
Point start = new Point(1, 9);
和我的第二个:
Point end = new Point(4, 9);
我想所有的起点和终点之间的点。因此,例如,我会想在数组中的2,9和3,9。 .NET有内置的东西吗?
由于点之间没有点,因此没有构建函数。数学在两点之间有一条线。在计算机图形学方面,线条可能是反锯齿的,所以不能四舍五入成为整数。
如果您正在寻找创建所有整数的快速方法,我猜Bresenhams-Line-Algorithm将成为您的选择。但是,这是不是建设成.NET,你必须自己编写它(或采取马修·沃森的实现):
http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
甚至还有专为做fasther算法,但我会去布氏。
这就是我最终做的。正如@Cody Gray在他的评论中提到的那样,有一条线上有无限的点。所以你需要指定你想要检索的点数。
var line = new Line(new Point(10, 15), new Point(297, 316));
var points = line.getPoints(20);
,将返回的20点的两个端点(含)之间均匀分布的一个点阵列:
我行类:
public class Line {
public Point p1, p2;
public Line(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
public Point[] getPoints(int quantity) {
var points = new Point[quantity];
int ydiff = p2.Y - p1.Y, xdiff = p2.X - p1.X;
double slope = (double)(p2.Y - p1.Y)/(p2.X - p1.X);
double x, y;
--quantity;
for (double i = 0; i < quantity; i++) {
y = slope == 0 ? 0 : ydiff * (i/quantity);
x = slope == 0 ? xdiff * (i/quantity) : y/slope;
points[(int)i] = new Point((int)Math.Round(x) + p1.X, (int)Math.Round(y) + p1.Y);
}
points[quantity] = p2;
return points;
}
}
用法。希望有所帮助!
你是一个坏蛋。 :O –
它也可以用于对角线吗? –
@BirajZalavadia绝对! –
我知道自从你第一次问这个问题已经很长时间了,但我最近在寻找类似的东西,发现这个维基(https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm),其中包含伪代码。
所以我已经实现了一个带有伪代码的函数来执行这个计算并将这些点添加到列表中。
public List<Point> GetPoints(Point p1, Point p2)
{
List<Point> points = new List<Point>();
// no slope (vertical line)
if (p1.X == p2.X)
{
for (double y = p1.Y; y <= p2.Y; y++)
{
Point p = new Point(p1.X, y);
points.Add(p);
}
}
else
{
// swap p1 and p2 if p2.X < p1.X
if (p2.X < p1.X)
{
Point temp = p1;
p1 = p2;
p2 = temp;
}
double deltaX = p2.X - p1.X;
double deltaY = p2.Y - p1.Y;
double error = -1.0f;
double deltaErr = Math.Abs(deltaY/deltaX);
double y = p1.Y;
for (double x = p1.X; x <= p2.X; x++)
{
Point p = new Point(x, y);
points.Add(p);
Debug.WriteLine("Added Point: " + p.X.ToString() + "," + p.Y.ToString());
error += deltaErr;
Debug.WriteLine("Error is now: " + error.ToString());
while (error >= 0.0f)
{
Debug.WriteLine(" Moving Y to " + y.ToString());
y++;
points.Add(new Point(x, y));
error -= 1.0f;
}
}
if (points.Last() != p2)
{
int index = points.IndexOf(p2);
points.RemoveRange(index + 1, points.Count - index - 1);
}
}
return points;
}
http://en.wikipedia.org/wiki/Bresenham's_line_algorithm – Patashu
有*摆在任意两点之间的无限多的*点。你想要他们吗? –
@CodyGray一个'Point'包含两个整数值。至少它在XNA的实现中是如此。 Patashu的链接可能是相关的。 –