在Java中使用for循环的重复行/条带

时间:2016-09-03 03:03:43

标签: java loops

我想在图像上绘制黑白条纹,在图像顶部水平和垂直切换每个第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像素,水平?

1 个答案:

答案 0 :(得分:0)

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

    // 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);
            }
        }
    }