如何使用嵌套for循环绘制尺寸*大小正方形的N * N网格?

时间:2017-04-20 01:07:49

标签: java image oop colors

使用颜色类在[][]颜色数组中绘制随机颜色的方块,这些颜色可以插入到n*n的网格中,每个方格也是size * size,图片类需要x, y和颜色参数。

我只在网格上设法drawSquare(),但需要填充随机颜色方块的完整网格。

import java.awt.Color;

public class ColorSquares {
    public static void main (String[]args){
        int N = Integer.parseInt(args[0]); //the n*n grid
        int size = Integer.parseInt(args[1]); // the size * size in a square
        Picture p = create(N, size);
        p.show();
        // Picture p=  Picture(N, size);

        // p.show();
    }
        public static void drawSquare(Picture p, int x0, int y0, int size, Color c)  {
        for (int x = x0; x < x0+size; x++)
            for (int y = y0; y < y0+size; y++)
                p.set(x,y,c);
    }


    /* Create a Picture which is an NxN grid of color squares
     * each square is size*size pixels */
    public static Picture create(int N, int size){
        Picture p = new Picture(N * size, N * size);

       Color[][] createColors = createColors(N);
        // the N represents the number of squares for the row to go through
       for (int r = 0 ; r < N  ; r++) {
           // the N also represents the number of squares the column goes through
           for (int c = 0; c < N ; c++) {
            drawSquare(p,r, c , size, createColors[r][c]);

            // drawSquare.set(r,c, createColors[r][c]);
             p.set(r,c,createColors[r][c]);
         }
        }

        return p ;
    }

    /* Create a two-dimensional NxN array of random Colors*/
    public static Color[][] createColors(int N){
        Color [][] colors = new Color [N][N]; // N*N board
     //   Color ranColor = (Color) generateRandomColor(Color);


        for ( int r = 0 ; r < N ; r++ ) {
            for ( int  c = 0; c < N ; c++) {
            colors[r][c] = generateRandomColor();



            }
        }

        return colors;
    }

    /* Generate a random Color (R,G,B each between 0 and 255) */
    public static   Color generateRandomColor(){

        //int colorValue = 0 + (int)(Math.random() * ((255 - 0) + 1));
       // int  colorValue = (int) Math.random (color);
        //return new  Color( colorValue,colorValue, colorValue);
        int red   = (int) (Math.random() * 256);
        int green = (int) (Math.random() * 256);
        int blue  = (int) (Math.random() * 256);

        Color randomColor = new Color( red, green, blue );
            return randomColor;
    }

}

0 个答案:

没有答案