【问题标题】:Drawing right triangle pixel by pixel, line by line?逐像素逐行绘制直角三角形?
【发布时间】:2015-04-30 20:32:45
【问题描述】:

这是我如何逐个像素、逐行(倒置)绘制直角三角形的代码:

double length = 10; double height = 5;
double aspectRatio = length / height;

double limit = 0.0;
int y = 0;

while (y < height) {
    int x = 0;

    while (x < (length - limit)) {
        drawPixel(x, y); // fill pixel on canvas with black at x, y
        x++;
    }

    limit += aspectRatio; // increase "step" how much to cut in length
    // this part here is wrong, the limit increased is too little

    y++;
}

我的问题是我没有从右上角延伸到左下角的斜边。这是因为我做错了计算,我不明白如何在网上搜索合适的术语来找到我需要的计算。

在我的代码中,aspectRatio 将变为 2.0,当第一条完整的线逐个像素绘制时,下一行将使用少 2.0 的像素绘制,下一行将使用少 2.0 的像素,等等。这意味着绘制了 5 条线看起来像这样:

[*][*][*][*][*][*][*][*][*][*]
[*][*][*][*][*][*][*][*][ ][ ]
[*][*][*][*][*][*][ ][ ][ ][ ]
[*][*][*][*][ ][ ][ ][ ][ ][ ]
[*][*][ ][ ][ ][ ][ ][ ][ ][ ]

但是我试图得到这样的东西(注意负空间匹配像素数量并且是对角垂直的):

[*][*][*][*][*][*][*][*][*][*]
[*][*][*][*][*][*][*][*][ ][ ]
[*][*][*][*][*][ ][ ][ ][ ][ ]
[*][*][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]

显然,这主要是一个数学问题,但是我不了解修复代码的必要方程式。我该怎么办?

【问题讨论】:

  • 为什么不计算小一排的三角形的纵横比?即 double aspectRatio = length / (height - 1.0) ;
  • 此代码还必须适用于任何长度/高度值,很抱歉我遗漏了它。例如。分别为 1300 和 700。它不适用于您的示例
  • 为什么该公式不适用于任何长度或高度(大于 1)?您是否对其进行了测试,但它给出了错误的结果?
  • 是的,我测试过,它不起作用。例如。在您的示例中,如果我们有长度 1300 和高度 700,而不是将 aspectRatio 计算为长度/高度,这将给出 1.85714285714286,而是希望计算为长度/(高度 - 1),或者在这种情况下为 1300 / 699,这将给1.85979971387697。这两个值之间的差异很小。斜边仍然是错误的。
  • 你是通过运行程序来测试它,还是仅仅通过计算来测试它?这个问题是一种栅栏柱错误:en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error 每行都是一个“栅栏柱”,如果有 h 行则有 h-1 步,所以你需要除以 h-1 才能在最后得到有效值积分

标签: java geometry aspect-ratio


【解决方案1】:

请记住,像素是正方形并且有一个区域,而 x/y 坐标只是指向正方形左上角的点。这可能是您混淆/不正确的斜边的原因。

试试这样的东西(未经测试):

while (y < height) {
    int x = 0;

    // add 0.5 to x/y coordinates to check that the center of the
    // pixel is inside your triangle, not the top left corner.
    while ((float)x + 0.5  < ((float)y + 0.5) * aspectRatio) {
        drawPixel(x, y); // fill pixel on canvas with black at x, y
        x++;
    }

    limit += aspectRatio; // increase "step" how much to cut in length
    // this part here is wrong, the limit increased is too little

    y++;
}

【讨论】:

  • 感谢您的帮助,此代码的工作方式非常不同,也会导致不正确的斜边。可能是什么原因?
猜你喜欢
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多