Matt
Matt

Reputation: 11347

How to resize an AWT Polygon in Java

Are there any in-built methods in the Java API which would allow me to resize a polygon?

Would it be quite a simple task to write my own method, or are there any others already made?

Upvotes: 1

Views: 6967

Answers (2)

finnw
finnw

Reputation: 48639

Yes, AffineTransform.createTransformedShape(Shape) will create a transformed copy of any Shape (which may be a Polygon or Path2D.)

Upvotes: 0

MeBigFatGuy
MeBigFatGuy

Reputation: 28588

No, nothing built in, altho, when you draw the polygon, you can draw the polygon with a transformation matrix applied which could scale the polygon for you. (or rotate, skew, etc, etc).

see

Graphics2D.setTransform(transform);

Lets assume you are drawing the polygon in a JPanel, and you have overridden the paintComponent method of JPanel. Cast the Graphics object to a Graphics2D object, and use transforms to scale it as appropriate:

public void paintComponent(Graphic g) {

     Graphics2D g2d = (Graphics2D) g;
     AffineTransform saveTransform = g2d.getTransform();

     try {
         AffineTransform scaleMatrix = new AffineTransform();
         scaleMatrix.scale(1.5, 1.5);
         //or whatever you want

         g2d.setTransform(scaleMatrix);
         g2d.drawPolygon(myPolygon);
     } finally {
         g2d.setTransform(saveTransform);
     }
}

Chances are you can set up the transformation matrix elsewhere (once) instead of each time in the paintComponent method, but i did here to show how to do it.

Also note, that this will move the polygon, you would probably want apply this to the transform:

  • add a translate to move the polygon to the origin
  • add a scale
  • add a translate to move the polygon back to the original position

in this way, the object doesn't move it just scales.

Upvotes: 2

Related Questions