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)); }
Jonas
source share