我想知道如何在 Java 绘图Panel
(而不是JPanel
)中旋转我已经绘制的东西(如线条)。
正在尝试通过连接 3 条线来旋转我创建的三角形:
g.drawLine(size, size, 2*size, size);
g.drawLine(size, size,size+size/2, size+(int)(size/2 * Math.sqrt(3)));
g.drawLine(2*size, size,size+size/2, size+(int)(size/2 * Math.sqrt(3)));
如何旋转它?
如果你想像
这样旋转一个点,那么你可以:
double startX; // <------------|
double startY; // <------------|
double endX; // <------------|
double endY; // <-define these
double angle; // the angle of rotation in degrees
绘制原始线条
g.setColor(Color.BLACK);
g.drawLine(startX, startY, endX, endY); //this is the original line
double length = Math.pow(Math.pow(startX-endX,2)+Math.pow(startY-endY,2),0.5);
double xChange = length * cos(Math.toRadians(angle));
double yChange = length * sin(Math.toRadians(angle));
绘制新的旋转线
g.setColor(Color.GRAY);
g.fillRect(0,0,1000,1000); //paint over it
g.setColor(Color.BLACK);
g.drawLine(startX, startY, endX + xChange, endY + yChange);
使用 graphics2D 和多边形
Graphics2D g2 = (Graphics2D) g;
int x2Points[] = {0, 100, 0, 100}; //these are the X coordinates
int y2Points[] = {0, 50, 50, 0}; //these are the Y coordinates
GeneralPath polyline =
new GeneralPath(GeneralPath.WIND_EVEN_ODD, x2Points.length);
polyline.moveTo (x2Points[0], y2Points[0]);
for (int index = 1; index < x2Points.length; index++) {
polyline.lineTo(x2Points[index], y2Points[index]);
};
g2.draw(polyline);
如果你想旋转它,只需重新做一遍,但添加,之前
g2.rotate(Math.toRadians(angle), centerX, centerY);
其中"角度"是要旋转的量,(centerX,centerY)是要旋转它的点的坐标。
我希望这有帮助