【问题标题】:Repeated lines/stripes using for loops in Java在 Java 中使用 for 循环的重复线条/条纹
【发布时间】:2016-09-03 13:48:58
【问题描述】:

我想在图像上绘制黑白条纹,每 20 列在图像顶部水平和垂直切换一次,同时保持在图像的边界内。到目前为止,我可以得到一个带有 1 像素宽的垂直条纹的黑色方块。我已经尝试通过切换东西来至少在我的水平线上获得细白条纹,但它仍然是垂直的。

public void zebraStripes() {

    Image img = ImageViewer.getImage();

    double numPixelsWide = img.getWidth();
    int numPixelsHigh = img.getHeight();


    Color c = Color.WHITE;
    Color b = Color.BLACK;


    double i = numPixelsWide;
    if (i % 20 == 0) {

        for (int x = 0; x < numPixelsHigh; x++) {
            for (int y = 0; y < i; y++) {
                img.setPixelColor(y, x, b);
                }

            for (int z = 19; z < i; z = z + 20) {
                    img.setPixelColor(z, x, c);
            }
        }
    }
}

// paint black and white stripes (left to right) on the image, switching
// every 20th row
public void jailBird() {

    Image img = ImageViewer.getImage();

    double numPixelsWide = img.getWidth();
    double numPixelsHigh = img.getHeight();

    Color c = Color.WHITE;
    Color b = Color.BLACK;

    double i = numPixelsHigh;
    if (i % 20 == 0) {

        for (int x = 0; x < numPixelsHigh; x++) {
            for (int y = 0; y < i; y++) {
                img.setPixelColor(y, x, b);
                }

            for (int z = 19; z < i; z = z + 20) {
                    img.setPixelColor(z, x, c);
            }
                }
            }
        }

}

如何让白色条纹为 20 像素宽和水平?

【问题讨论】:

  • 如需更好的帮助,请尽快考虑发布minimal reproducible example。 C 代表 Complete - 它应该包括编译和运行所需的所有内容。
  • 不要在双打上使用==。你的问题的一部分可能是一个错误,numPixlesHigh 可以被 20 整除,但是由于双精度问题i % 20 不能精确地产生 0.0。不太可能,但总比抱歉更安全。

标签: java loops


【解决方案1】:

未经测试!希望它能让你继续前进。

    // paint a 20 pixels wide horizontal line for every 40 pixels
    for (int y = 0; y < numPixelsHigh; y += 40) {
        // paint a stripe
        for (int ys = y; ys < y + 20; ys++) {
            for (int x = 0; x < numPixelsWide; x++) {
                img.setPixelColor(x, ys, Color.BLACK);
            }
        }
    }

【讨论】:

  • 它可能会尝试在图像之外绘制,因为ys 可以上升到numPixelsHisgh + 18。如果出现问题,我相信您可以自行修复。
猜你喜欢
  • 2019-03-13
  • 2021-08-18
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多