1

我想知道如何旋转我已经在 J​​ava 绘图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)));

我如何旋转它?

4

2 回答 2

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);
于 2013-10-21T20:49:14.193 回答
0

使用 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) 是您要旋转的点的坐标。

我希望这有帮助

于 2013-10-20T21:27:59.743 回答