Java - Scaling a canvas about a particular point

326 views Asked by At

I am more or less finished a very simple planetary gravity simulator using Newtonian physics. It can transform and scale the planets for pan and zoom. This works fine, mouse input and everything. The problem I have is more aesthetic than anything else. Since the origin of the canvas is at the top left corner of the window (within a JPanel, within a JFrame), everything scales about that point. I was wondering is there any way to either set the origin to the center of the screen, or to scale about a particular point? (Even though AffineTransform.scale() only has one constructor, with scaleX and scaleY as the args). I have tried setting the bounds of the canvas as negative numbers as such:

canvas.setBounds(-width/2, -height/2, width/2, height/2);

(Width and height are the screen size).

This obviously doesn't work as negative numbers are outside the co-ords of the panel.

So does anyone know anyway of accomplishing this? Either setting the centre of the screen as the origin or scaling about a particular point rather than the origin?

1

There are 1 answers

0
Andrew Thompson On BEST ANSWER

The trick here is to concatenate instances of AffineTransform.

  1. Move the entire rendering so the center is at the origin.
  2. Scale the rendering.
  3. Move the center of the rendering (now at the origin) back to the center of the view.