AffineTransform: how to scale only one shape Triangle

I have this code:

import javax.swing.*; import java.awt.*;  public class Test  {     public static void main(String[] args) {         JFrame window = new JFrame();         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         window.setBounds(30, 30, 300, 300);         window.getContentPane().add(new MyCanvas());         window.setVisible(true);       } }  class MyCanvas extends JComponent {      public void paint(Graphics g) {         g.drawRect (10, 10, 100, 100);         Polygon triangle = new Polygon(new int[] {100, 150, 200}, new int[] {200, 100, 200}, 3);         g.drawPolygon(triangle);     } } 

It draws this:

enter image description here

I want to scale only Triangle, so it becomes thrice is big:

enter image description here

I understand that I need to use AffiniteTransform, but I don’t understand how.

I only know that I need the scaling instance:

AffineTransform at = AffineTransform.getScaleInstance(3, 3); 

All answers I’ve seen were very confusing or just used g2d.setTransform(at) which doesn’t seem to be what I need, seeing as the square is supposed to stay the same size.

EDIT: And how do I scale a Triagle, while keeping its leftmost coordinate at the same location? (leftmost (x,y) stays the same)

New code:

public class Test  {     public static void main(String[] args) {         JFrame window = new JFrame();         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         window.setBounds(30, 30, 300, 300);         window.getContentPane().add(new MyCanvas());         window.setVisible(true);       } }  class MyCanvas extends JComponent {      public void paint(Graphics g) {         g.drawRect (10, 10, 100, 100);         Polygon triangle = new Polygon(new int[] {100, 150, 200}, new int[] {200, 100, 200}, 3);          AffineTransform at = AffineTransform.getScaleInstance(1.5, 1.5);         ((Graphics2D) g).setTransform(at);         g.drawPolygon(triangle);         ((Graphics2D) g).setTransform(AffineTransform.getScaleInstance(1,1)); validate();       } } 

gives this:

enter image description here

The triangle shifts as it gets scaled.

Is it possible to keep the triangle at the same spot – that is to keep its leftmost bottom corner at the same spot?

enter image description here

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.