如何在java图形中使用x和y坐标定位形状?
我试图将红色六边形重新定位到下图中黑色箭头指向的矩形的中心 但是我找不到放x和y坐标的地方如何在java图形中使用x和y坐标定位形状?,java,graphics,polygon,Java,Graphics,Polygon,我试图将红色六边形重新定位到下图中黑色箭头指向的矩形的中心 但是我找不到放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
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);
}
public void poligon(图g){
Graphics2D g2d=(Graphics2D)g;
多边形pol;
//六边形顶点的x和y坐标
int x[]={375,400,450,475,450,400};
int y[]={150100100150200200};
//x和y坐标偏移多少
int xOffset=100;
int-yOffset=20;
//偏移六边形,直到缩小到正确的位置
对于(int i=0;i
注意:有更简单的方法来计算中心坐标,但使用您提供的代码,这是我可以提供的唯一解决方案。我认为您总是在示例中输入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做实验之后。这样你就不会破坏你的多边形,你可以安全地移动它
祝你编码愉快 对不起,我还不能给你打电话