繁体   English   中英

如何在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 坐标。

我只会尝试随机数量,缩小要添加和减去的确切数量。 例如,乍一看,您需要将 100 添加到x[]并从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 进行实验。 这样你就不会破坏你的多边形,你可以安全地移动它。

玩得开心编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM