How can I use JPanel using a different quadrant for coordinates?

I would like to draw some shapes on JPanel by overriding paintComponent . I would like to be able to pan and zoom. Panning and zooming is easy to use with AffineTransform and the setTransform method of a setTransform object. After that, I can simplify drawing shapes with g2.draw(myShape) . Shapes are defined using "world coordinates", so it works great when panning, and I have to translate them into canvas / JPanel coordinates before drawing.

Now I would like to change the quadrant of the coordinates. From the 4th quadrant, which JPanel and the computer often use in the first quadrant, which users are most familiar with. X is the same, but the Y-ax should increase up, not down. It is easy to redefine origami on new Point(origo.x, -origo.y);

But how to draw shapes in this quadrant? I would like to save the coordinates of the figures (defined in world coordinates), and not have them in the coordinates of the canvas. So I need to somehow convert them or convert a Graphics2D object, and I would like to do this efficiently . Can I do this with AffineTransform too?

My code for drawing:

  public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.blue); AffineTransform at = g2.getTransform(); at.translate(-origo.x, -origo.y); at.translate(0, getHeight()); at.scale(1, -1); g2.setTransform(at); g2.drawLine(30, 30, 140, 20); g2.draw(new CubicCurve2D.Double(30, 65, 23, 45, 23, 34, 67, 58)); } 
0
source share
1 answer

This is a response to the cuff, so it has not been tested, but I think it will work.

Translate to (0, height). This should move the start to the bottom left.

Scale to (1, -1). This should flip it around the x axis.

I do not think that the order of operations matters in this case.

+1
source

All Articles