Search code examples
javaawtgraphics2d

Creating 3x3 checkerboard over a picture using Graphics2D


I want to create an overlay of a 3x3 checkerboard, where the non-solid squares should be transparent.

I don't want to iterate the pixels, but rather just draw squares using Graphics2D to create a checkerboard. (Do I need a for loop, an if statement, or both?)
Here's my code so far:

Picture myPict = new Picture(myPathName);
myPict.show();
Graphics2D graphicsObj = myPict.getGraphics2D();
final int WIDTH = myPict.getWidth() / 3;
final int HEIGHT = myPict.getHeight() / 3;
for (int i = 0; i > WIDTH; i = WIDTH * 2) {
    Rectangle2D.Double shape1 = new Rectangle2D.Double(WIDTH, HEIGHT, 0, 0);
    graphicsObj.draw(shape1);
}

Solution

  • I'd use a combined (double) for loop/if statement for drawing the solid parts of the checkerboard. In pseudo-code it might be expressed as:

    draw image
    for each row {
        for each column {
          if 'odd' square number {
            graphics fill rectangle
          }
      }
    }