Graphics2D does PostModern

2019-09-04 13:20发布

问题:

In the following code changing fill to draw produces unexpected results. The attached image demonstrates the undesired but much appreciated postmodern effect caused by drawing the red and green rectangles.

The affine transform should not be part of the problem, but as Holmes said, once you rule out all other possibilities ... So, I will explain the transform. I solved a bunch of equations to figure out how to make the window show a cartesian coordinate system with (-2, -2) in the lower left and (+2, +2) in the upper right.

This is a self-contained example. Try changing any of the draws to a fill or vice versa to achieve your own custom art that you can frame in the Oracle office.

I am using Java SE 7, JDK 1.7.0_21!

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class G {

  public static void main (String [] args) {
    JFrame frame = new JFrame(G.class.getCanonicalName());
    JComponent component = new JComponent() {
      private static final long serialVersionUID = 1L;

      @Override
      protected void paintComponent (Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        AffineTransform xform = new AffineTransform(getWidth() / 4, 0, 0, - getHeight() / 4, getWidth() / 2, getHeight() / 2);
        g2.setTransform(xform);
        paint2D(g2);
        g2.dispose();
      }

      protected void paint2D (Graphics2D g2) {
        g2.setColor(Color.RED);
        g2.draw(new Rectangle2D.Double( 0,  0, 1, 1));
        g2.setColor(Color.GREEN);
        g2.draw(new Rectangle2D.Double(-1, -1, 1, 1));
        g2.setColor(Color.BLUE);
        g2.fill(new Rectangle2D.Double(-1,  0, 1, 1));
        g2.setColor(Color.YELLOW);
        g2.fill(new Rectangle2D.Double( 0, -1, 1, 1));
      }
    };
    frame.setLayout(new BorderLayout());
    frame.add(component, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);
  }
}

回答1:

it is the 1 unit default stroke setting. i increased the coordinate space from -20 to +20 in each dimension and drew 10 unit wide and high rectangles which confirmed the problem as the image below shows.