【问题标题】:How rotate rectangle around corner on applet?如何在小程序上围绕角落旋转矩形?
【发布时间】:2016-09-19 16:54:25
【问题描述】:

我想围绕一个角旋转矩形,但我现在不知道如何确定角的新坐标。旋转可以在任何角落。 是否存在另一种旋转方式?

有人可以帮我吗?

screenshot of my applet

import java.applet.*;
import java.awt.*;

public class MainApplet extends Applet implements Runnable {

int width, height;
int i = 0;
Thread t = null;
boolean threadSuspended;

public void init() {
    width = getSize().width;
    height = getSize().height;
    setBackground(Color.black);
}

public void destroy() {}


public void start() {
    if (t == null) {
        t = new Thread(this);
        threadSuspended = false;
        t.start();
    } else {
        if (threadSuspended) {
            threadSuspended = false;
            synchronized (this) {
                notify();
            }
        }
    }
}

public void stop() {
    threadSuspended = true;
}

public void run() {
    try {
        while (true) {
            ++i;
            if (i == 359) {
                i = 0;
            }
            showStatus("i is " + i);

            if (threadSuspended) {
                synchronized (this) {
                    while (threadSuspended) {
                        wait();
                    }
                }
            }
            repaint();
            t.sleep(100);  // interval given in milliseconds
        }
    } catch (InterruptedException e) {
    }
}

public void paint(Graphics g) {
    g.setColor(Color.green);

    g.drawRect(200,150, (int) (50*Math.cos(i)-100*Math.sin(i)+200-200*Math.cos(i)+150*Math.sin(i)),
                        (int) (50*Math.sin(i)+100*Math.cos(i)+150-200*Math.sin(i)-150*Math.cos(i)));
}
}

【问题讨论】:

  • 1) 为什么要编写小程序?如果是老师指定的,请参考Why CS teachers should stop teaching Java applets。 2) 为什么使用 AWT?请参阅this answer,了解许多放弃 AWT 使用支持 Swing 的组件的充分理由。
  • 这是老师的任务。
  • “这是老师的任务。”好的。给他们那个链接..

标签: java animation graphics awt java-2d


【解决方案1】:

你可以使用Graphics2D.rotate(theta, double x, double y)方法。

public void paint(Graphics g){
  //Create Graphics2D object:
  Graphics2D g2d = (Graphics2D) g.create();

  //Create rectangle of origin (0,0), w=30, h=50
  Rectangle rectangle = new Rectangle();
  rectangle.setBounds(0,0,30,50);

  //Rotate rectangle by 1 radian(Math.PI) from the bottom corner
  g2d.rotate(Math.PI, rectangle.x + rectangle.width/2, rectangle.y + rectangle.height/2);

  //Draw rectangle
  g2d.draw(rectangle);
}

【讨论】:

  • @Sergo 我添加了 cmets 来解释它是如何工作的。如果你用我写的方法替换你的“paint”方法,那么你会看到矩形可以旋转。请记住“.rotate(theta, x, y)” theta 的单位是弧度,而不是度数。
  • 我换了,但他不动。您是否进行了其他更改?
  • public void paint(Graphics g){ Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.green);矩形矩形 = 新矩形();矩形.setBounds(100,100,50,70); g2d.rotate(Math.PI*0.00555*i, rectangle.x, rectangle.y); g2d.draw(矩形); } //然后改变 sleep(10)
  • 谢谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2019-03-07
  • 2018-06-08
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
相关资源
最近更新 更多