如何旋转绘图面板中绘制的一系列线条和形状?

时间:2013-10-20 13:11:13

标签: java graphics drawing awt panel

我想知道如何在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)));

如何旋转呢?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

使用graphics2D和Polygons

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);

其中“angle”是您想要旋转它的数量,(centerX,centerY)是您想要旋转它的点的坐标。

我希望这会有所帮助