【问题标题】:How to rotate a series of lines and shapes drawn in drawing Panel?如何旋转绘图面板中绘制的一系列线条和形状?
【发布时间】:2013-10-28 22:54:11
【问题描述】:

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

如何旋转它?

【问题讨论】:

  • 1) 为什么选择 AWT 而不是 Swing?请参阅Swing extras over AWT 上的此答案,因为有很多放弃使用 AWT 组件的充分理由。如果您需要支持较旧的基于 AWT 的 API,请参阅 Mixing Heavyweight and Lightweight Components。 2) 使用AffineTransform - 尽管注意这不适用于“已经绘制”的东西。有必要重新绘制面板。
  • 这是为了上课,所以我的老师要求我使用 awt,你能提供一个如何使用 affineTransform 旋转单行的例子
  • "..你能举个例子吗" 我已经提供了many examples。如果您无法从这些示例中获得有效的解决方案,请发布您的最佳尝试SSCCE

标签: java graphics drawing awt panel


【解决方案1】:

如果你想像这样旋转一个点,那么你可以:

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

【讨论】:

    【解决方案2】:

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

    希望对你有帮助

    【讨论】:

    • 这很棒,但我实际上只是想将一条线旋转一定的度数,同时仍保持线起始点相同
    • @LouisB 事实证明,这并不像听起来那么简单。您要么使用 Graphics2D.rotate(),要么自己使用一些基本的触发。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多