001package jmri.util.swing;
002
003import java.awt.Color;
004import java.awt.Graphics2D;
005import java.awt.image.BufferedImage;
006import org.slf4j.Logger;
007import org.slf4j.LoggerFactory;
008
009/**
010 * Common utility to draw colored rectangular Image.
011 *
012 * @author Egbert Broerse copyright (c) 2017
013 */
014public class DrawSquares {
015
016    /**
017     * Produce a grid of contrasting squares. Ideally the width and height match
018     * the parent frame size.
019     *
020     * @param width  image width in pixels
021     * @param height image height in pixels
022     * @param dim    length of sides of squares in pixels
023     * @param color1 background color
024     * @param color2 contrasting fill color
025     * @return the image with a grid of squares
026     */
027    public static BufferedImage getImage(int width, int height, int dim, Color color1, Color color2) {
028        Color sqColor = new Color(235, 235, 235); // light gray
029        Color bgColor = Color.white;
030        BufferedImage result;
031        int w = 500;
032        int h = 500;
033        if (width > 0) {
034            w = width;
035        }
036        if (height > 0) {
037            h = height;
038        }
039        if (color1 != null) {
040            bgColor = color1;
041        }
042        if (color2 != null) {
043            sqColor = color2;
044        }
045        // paint alternate squares
046        result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
047        Graphics2D g2d = result.createGraphics();
048        g2d.setColor(bgColor);
049        g2d.fillRect(0, 0, w, h); // plain rect background
050        if (sqColor != bgColor) {
051            g2d.setColor(sqColor);
052            for (int j = 0; j <= (w / dim); j++) {
053                for (int k = 0; k <= (h / dim); k++) {
054                    if ((j + k) % 2 == 0) { // skip every other square
055                        g2d.fillRect(j * dim, k * dim, dim, dim); // gray squares
056                    }
057                }
058            }
059        }
060        g2d.dispose();
061
062        log.debug("DrawSquares ready");
063        return result;
064    }
065
066    private static final Logger log = LoggerFactory.getLogger(DrawSquares.class);
067
068}