我正在尝试使用 java 2d 图形库绘制图形,我认为我已经有了它。我想在坐标系中绘制,其中 0,0 位于面板左边缘的中心。我使用了以下代码,它似乎给了我我需要的结果。
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);
}
这绘制了以窗口为中心的原点。
当我添加菜单时,问题就出现了。然后原点在 y 方向上偏移大约是菜单大小的两倍,高于应有的高度。我是否需要考虑添加到面板的菜单和其他容器的大小?
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);
}
可以了,谢谢你的帮助
最佳答案
您可以尝试概述的方法 here 。重写paintComponent()
以获取相对于封闭面板而不是封闭框架的图形上下文。
要将原点置于左边缘居中,请使用
g2d.translate(0, h / 2);
要获得直立的笛卡尔坐标,请使用
g2d.scale(1, -1);
关于Java 2d 坐标变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23204874/