2

我正在使用 Java2d 开发应用程序。我注意到的奇怪的事情是,原点在左上角,正 x 向右,正 y 向下增加。

有没有办法将原点左下角移动?

谢谢你。

4

5 回答 5

5

您将需要进行缩放和翻译。

在您的paintComponent方法中,您可以这样做:

public void paintComponent(Graphics g)
{
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(0, -height);
    g2d.scale(1.0, -1.0);
    //draw your component with the new coordinates

    //you may want to reset the transforms at the end to prevent
    //other controls from making incorrect assumptions
    g2d.scale(1.0, -1.0);
    g2d.translate(0, height);
}

我的 Swing 有点生锈,但这应该可以完成任务。

于 2010-05-14T03:27:21.823 回答
2

我们可以使用以下方法轻松解决问题,

public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
// Flip the sign of the coordinate system
g2d.translate(0.0, getHeight());
g2d.scale(1.0, -1.0);
......
}
于 2013-09-18T08:56:14.877 回答
0

你试过Graphics2D.translate()吗?

于 2010-05-14T02:09:50.347 回答
0

你会想要习惯它。就像卢克提到的那样,从技术上讲,您可以对图形实例应用变换,但这最终会对性能产生负面影响。

仅进行平移可以将 0,0 的位置移动到左下角,但沿正轴的移动仍将在 x 方向上向右,在 y 方向上向下,因此您唯一要做的就是将所有内容绘制到屏幕外。您需要进行旋转来完成您的要求,这会将弧度计算的开销添加到图形实例的变换矩阵中。这不是一个好的权衡。

于 2010-05-14T19:40:55.167 回答
0

只是为了以后参考,我不得不在我的代码中交换调用scale的顺序。translate也许这将有助于将来的某人:

@Test
public void bottomLeftOriginTest() throws IOException {
    int width = 256;
    int height = 512;

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);    
    Graphics2D ig = bi.createGraphics();
    // save the "old" transform
    AffineTransform old = ig.getTransform();

    // origin is top left:
    // update graphics object with the inverted y-transform
    if (true) { /* order ok */
        ig.scale(1.0, -1.0);
        ig.translate(0, -bi.getHeight());
    } else {
        ig.translate(0, -bi.getHeight());
        ig.scale(1.0, -1.0);
    }

    int xPoints[] = new int[] { 0, width, width };
    int yPoints[] = new int[] { 0, height, 0 };
    int nPoints = xPoints.length;
    ig.setColor(Color.BLUE);
    ig.fillRect(0, 0, bi.getWidth(), bi.getHeight());

    ig.setColor(Color.RED);
    ig.fillPolygon(xPoints, yPoints, nPoints);

    // restore the old transform
    ig.setTransform(old);

    // Export the result to a file
    ImageIO.write(bi, "PNG", new File("origin.png"));
}

左下原点

于 2018-11-27T08:53:27.897 回答