How can I draw on JPanel using another quadrant for the coordinates?

别来无恙 提交于 2019-12-08 10:56:20

问题


I would like to draw some shapes on a JPanel by overriding paintComponent. I would like to be able to pan and zoom. Panning and zooming is easy to do with AffineTransform and the setTransform method on the Graphics2D object. After doing that I can easyli draw the shapes with g2.draw(myShape) The shapes are defined with the "world coordinates" so it works fine when panning and I have to translate them to the canvas/JPanel coordinates before drawing.

Now I would like to change the quadrant of the coordinates. From the 4th quadrant that JPanel and computer often uses to the 1st quadrant that the users are most familiar with. The X is the same but the Y-axe should increase upwards instead of downwards. It is easy to redefine origo by new Point(origo.x, -origo.y);

But How can I draw the shapes in this quadrant? I would like to keep the coordinates of the shapes (defined in the world coordinates) rather than have them in the canvas coordinates. So I need to transform them in some way, or transform the Graphics2D object, and I would like to do it 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));
        }

回答1:


This is an off the cuff answer, so it's untested, but I think it will work.

Translate by (0, height). That should reposition the origin to the lower left.

Scale by (1, -1). That should flip it about the x axis.

I don't think the order of operations matters in this case.



来源:https://stackoverflow.com/questions/2563618/how-can-i-draw-on-jpanel-using-another-quadrant-for-the-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!