【问题标题】:How to position a shape using x and y coordinates in java graphics?如何在 java 图形中使用 x 和 y 坐标定位形状?
【发布时间】:2019-03-03 11:30:45
【问题描述】:

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

我找不到放置 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);
}

【问题讨论】:

    标签: java graphics polygon


    【解决方案1】:

    目前,您的六边形看起来在您希望它居中的位置的上方和左侧。因此,对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);
    }
    

    注意:计算中心坐标的方法要简单得多,但使用您提供的代码,这是我能提供的唯一解决方案。

    【讨论】:

    • 抱歉我还不能给你代表
    【解决方案2】:

    我认为您总是在示例中输入 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 的基数进行实验。这样您就不会破坏多边形并且可以安全地移动它。

    祝你编码愉快!

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      相关资源
      最近更新 更多