如何使用另一个象限作为坐标在 JPanel 上绘图?
我想通过重写 paintComponent
在 JPanel 上绘制一些形状。我希望能够平移和缩放。使用 AffineTransform
和 Graphics2D
对象上的 setTransform
方法可以轻松实现平移和缩放。完成此操作后,我可以使用 g2.draw(myShape) 轻松绘制形状。形状是使用“世界坐标”定义的,因此平移时效果很好,我必须将它们转换到画布/JPanel绘制前的坐标。
现在我想更改坐标的象限。从JPanel和计算机经常使用的第四象限到用户最熟悉的第一象限。 X 轴相同,但 Y 轴应向上而不是向下增加。通过 new Point(origo.x, -origo.y); 重新定义 origo 很容易;
但是我怎样才能绘制这个象限中的形状?我想保留形状的坐标(在世界坐标中定义)而不是在画布坐标中。因此,我需要以某种方式转换它们,或者转换 Graphics2D
对象,并且我希望高效地做到这一点。我也可以使用 AffineTransform
来做到这一点吗?
我的绘图代码:
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));
}
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));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个即兴的答案,因此未经测试,但我认为它会起作用。
按 (0, 高度) 平移。这应该将原点重新定位到左下角。
按 (1, -1) 缩放。这应该绕 x 轴翻转它。
我认为在这种情况下操作顺序并不重要。
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.