如何在 java 图形中使用 x 和 y 坐标定位形状?

How to position a shape using x and y coordinates in java graphics?

我正在尝试将红色六边形重新定位到下图中黑色箭头指向的矩形的中心。

不过我找不到放置 x 和 y 坐标的位置。

public void poligon(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Polygon pol;

    int x[] = {375, 400, 450, 475, 450, 400};
    int y[] = {150, 100, 100, 150, 200, 200};

    pol = new Polygon(x, y, x.length);
    g2d.setPaint(Color.red);
    g2d.fill(pol);
}

目前,您的六边形看起来位于您希望它居中的位置的上方和左侧。因此,x[]中的每个整数添加相同的数量,并且y[]中的每个整数中减去相同的数量。这些数组中的整数表示六边形顶点的 x 和 y 坐标。

我会尝试随机数量来缩小要加减的确切数量。例如,乍一看,您似乎需要在 x[] 上加 100,并从 y[] 中减去 20。您可以对值进行硬编码:

int x[] = {375 + 100, 400 + 100, 450 + 100, 475 + 100, 450 + 100, 400 + 100};
int y[] = {150 - 20, 100 - 20, 100 - 20, 150 - 20, 200 - 20, 200 - 20};

或者您可以节省一些时间来缩小值范围,只需 运行 一个循环:

public void poligon(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Polygon pol;

    // the x and y coordinates of the vertices of your hexagon
    int x[] = {375, 400, 450, 475, 450, 400};
    int y[] = {150, 100, 100, 150, 200, 200};

    // how much to offset the x and y coordinates by
    int xOffset = 100;
    int yOffset = 20;

    // offset your hexagon until you narrow down the right position
    for(int i = 0; i < x.length; ++i) {
        x[i] += xOffset;
        y[i] -= yOffset;
    }

    pol = new Polygon(x, y, x.length);
    g2d.setPaint(Color.red);
    g2d.fill(pol);
}

注意:有更简单的方法来计算中心坐标,但是对于您提供的代码,这是我可以提供的唯一解决方案。

我认为您总是在示例中输入 x 和 y 坐标来制作多边形。 在您的示例中,多边形点上的 x 位置为:375、400、450、475、450、400,相同点的 y 位置为 150、100、100、150、200、200。

我会尝试找出点之间的差异并保存。在您的示例中,您可以获得 375 作为 x 的基数。所以数组内的点将是:

int baseX = 375;
int x[] = {baseX, baseX + 25, baseX + 75, baseX + 100, baseX + 75, baseX + 25};

请对y做同样的事情。之后用 baseX 和 baseY 进行实验。这样你就不会破坏你的多边形,你可以安全地移动它。

编码愉快!