Java Graphics2d:如何使用 int 值平滑地旋转十二边形
Java Graphics2d: how to rotate a dodecagon smoothly using int values
我用这个函数创建了一个十二边形:
private void getPoints(int x0, int y0,int r,int noOfDividingPoints)
{
double angle1 = 1;
x = new int[noOfDividingPoints];
y = new int[noOfDividingPoints];
for(int i = 0 ; i < noOfDividingPoints ;i++)
{
angle1 = i * (360/noOfDividingPoints);
x[i] = (int) Math.round(x0 + r * Math.cos(Math.toRadians(angle1)));
y[i] = (int) Math.round(y0 + r * Math.sin(Math.toRadians(angle1)));
}
}
然后我围绕一个中心旋转所有点:
for (int i = 0; i < SLICES; i++) {
int x1 = x[i] - center.x;
int y1 = y[i] - center.y;
int x2 = (int) Math.round(x1 * Math.cos(radian) - y1 * Math.sin(radian));
int y2 = (int) Math.round(x1 * Math.sin(radian) + y1 * Math.cos(radian));
x[i] = x2 + center.x;
y[i] = y2 + center.y;
}
有了这个我终于划清了界线:
for (int i = 0; i < SLICES; i++) {
g.drawLine(center.x, center.y, x[i], y[i]);
if (i != 0 ) {
g.drawLine(x[i-1], y[i-1], x[i], y[i]);
} else {
g.drawLine(x[i], y[i], x[x.length-1], y[x.length-1]);
}
}
问题:
十二边形旋转,但旋转使顶点变形,使形状略微不规则;它在旋转过程中发生变化:发生这种情况是因为 Math.round().
从 double 到 int 的转换
如果不使用 Math.round(),十二边形会折叠到中心。
如何在不改变形状的情况下使用 int 值?我必须使用双打吗?
我没有检查过你的代码,但专注于你的观察 "making the shape slightly irregular" 和 "Without using Math.round() the dodecagon collapses to the center"。您正在累积计算的错误。您必须重写代码,以便累积旋转角度,然后根据原始形状对显示进行一次计算。这样轮(或在 int 转换的情况下截断)不会累积。
即而不是
X = X * RotationStep
你做的每一步
Rotation += RotationStep;
X = originalX * Rotation
我用这个函数创建了一个十二边形:
private void getPoints(int x0, int y0,int r,int noOfDividingPoints)
{
double angle1 = 1;
x = new int[noOfDividingPoints];
y = new int[noOfDividingPoints];
for(int i = 0 ; i < noOfDividingPoints ;i++)
{
angle1 = i * (360/noOfDividingPoints);
x[i] = (int) Math.round(x0 + r * Math.cos(Math.toRadians(angle1)));
y[i] = (int) Math.round(y0 + r * Math.sin(Math.toRadians(angle1)));
}
}
然后我围绕一个中心旋转所有点:
for (int i = 0; i < SLICES; i++) {
int x1 = x[i] - center.x;
int y1 = y[i] - center.y;
int x2 = (int) Math.round(x1 * Math.cos(radian) - y1 * Math.sin(radian));
int y2 = (int) Math.round(x1 * Math.sin(radian) + y1 * Math.cos(radian));
x[i] = x2 + center.x;
y[i] = y2 + center.y;
}
有了这个我终于划清了界线:
for (int i = 0; i < SLICES; i++) {
g.drawLine(center.x, center.y, x[i], y[i]);
if (i != 0 ) {
g.drawLine(x[i-1], y[i-1], x[i], y[i]);
} else {
g.drawLine(x[i], y[i], x[x.length-1], y[x.length-1]);
}
}
问题:
十二边形旋转,但旋转使顶点变形,使形状略微不规则;它在旋转过程中发生变化:发生这种情况是因为 Math.round().
从 double 到 int 的转换如果不使用 Math.round(),十二边形会折叠到中心。
如何在不改变形状的情况下使用 int 值?我必须使用双打吗?
我没有检查过你的代码,但专注于你的观察 "making the shape slightly irregular" 和 "Without using Math.round() the dodecagon collapses to the center"。您正在累积计算的错误。您必须重写代码,以便累积旋转角度,然后根据原始形状对显示进行一次计算。这样轮(或在 int 转换的情况下截断)不会累积。
即而不是
X = X * RotationStep
你做的每一步
Rotation += RotationStep;
X = originalX * Rotation