[英]Java 2d coordinate transformation
I am trying to plot a graph using the java 2d graphics library and I thought I had it. 我正在尝试使用java 2d图形库绘制图形,我以为自己有图形。 I want to plot in the coordinate system where 0,0 is in the center of the panel on the left edge.
我想在坐标系中绘制,其中0,0在面板的左边缘中心。 I used the following code and it seemed to give me the result I needed.
我使用了以下代码,它似乎给了我所需的结果。
private void doDraw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform saveAT = g2d.getTransform();
// get the height of the panel
int height = getHeight();
// Find the middle of the panel
double yTrans = ((double)height)/2.0;
AffineTransform tform = AffineTransform.getTranslateInstance( 0.0, yTrans);
g2d.setTransform(tform);
//draw the line for the x-axis.
g2d.drawLine(0, 0, 100, 0);
//restore the old transform
g2d.setTransform(saveAT);
}
This plotted the origin centered in the window. 这将原点绘制在窗口中心。
The problem shows itself when I added a menu. 当我添加菜单时,问题就显示出来了。 Then the origin was offset in the y direction about twice the size of the menu higher then it should be.
然后,原点沿y方向偏移,大约是菜单尺寸的两倍,应该是它的两倍。 Do I need to account for the size of the menu and other containers that I add to the panel?
我需要考虑添加到面板中的菜单和其他容器的大小吗?
private void doDraw(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
int height = getHeight();
double yTrans = ((double)height)/2.0;
AffineTransform tform = AffineTransform.getTranslateInstance( 0.0, yTrans);
g2d.transform(tform);
//draw the line for the x-axis.
g2d.drawLine(0, 0, 100, 0);
}
works, thank you for your help 可以,谢谢你的帮助
You might try the approach outlined here . 您可以尝试此处概述的方法。 Override
paintComponent()
to obtain a graphics context relative to the enclosing panel, rather than the enclosing frame. 重写
paintComponent()
以获得相对于封闭面板而不是封闭框架的图形上下文。
To center the origin at the left edge, use 要将原点放在左边缘居中,请使用
g2d.translate(0, h / 2);
To get upright, cartesian coordinates, use 要获得直立的直角坐标,请使用
g2d.scale(1, -1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.