Search code examples
javarotationgraphics2d

Java rotate issue


When I try and apply a rotation to the current g2d object, it doesn't rotate it, it renders it in the same place (in my context on top of the other). From what I understand of the rotate method, it applies a transformation to the current graphics context, transforming the pixels of any rendering that comes after it (this might be where I'm going wrong). Here's the code in question:

@Override
  public void paint(final Graphics graphics) {
    super.paint(graphics);
    final Graphics2D g2d = (Graphics2D) graphics;
    ....
    ....
    g2d.setColor(Color.RED);
    g2d.setStroke(new BasicStroke(SMALL_LINE_THICKNESS));
    if (isLattice1Drawn) {
      g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1));
      // lattice1 and lattice2 are Polygon objects
      g2d.draw(lattice1);
      // This fades in the second Polygon over the first
      g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
      // This line should rotate it, but doesn't
      g2d.rotate(Math.toRadians(210));
      g2d.draw(lattice2);
      .....

Thanks, Mike

Edit 1 As a suggestion from Jeff, I tried having just the rotation and drawing in paint, leaving me with the following code:

@Override
public void paint(final Graphics graphics) {
  super.paint(graphics);
  final Graphics2D g2d = (Graphics2D) graphics;
  g2d.rotate(Math.toRadians(210));
  g2d.draw(lattice2);
  return;
  // Rest of paint .................

Unfortunately this did not help, any other suggestions would be most welcome.

Edit 2: When I don't call rotate, the polygon is rendered, however when I do nothing happens. Can anyone explain this?


Solution

  • What I understand from Edit 2 is: the rotation actually works. However, since rotation is around origin the rotated coordinates of the polygon ends up outside of the visible area. You can test this by rotating smaller degrees.

    Then, if the desired operation is to rotate a polygon around its center of mass, use the following Graphics2D method instead:

    void rotate(double theta, double x, double y)