java - 如何在小程序上绕角旋转矩形?

标签 java animation graphics awt java-2d

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

有人可以帮助我吗?

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

最佳答案

您可以使用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);
}

关于java - 如何在小程序上绕角旋转矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37380325/

相关文章:

Javascript回调函数故障

javascript - 使用 JQuery 代替 CSS 的幻灯片动画

java - 如何在JLayeredPane的任意一层上使用图形(Piant组件)

java - 使用Java图形打印关于线的线标签

java - Jacoco 离线检测 Gradle 脚本

java - 在获取 NPE 的 Activity 中调用 Fragment 方法

java - Map 方法引用链

java - 媒体播放器在 R.raw 上失败 - Android

android - Android 中的滑动动画

iphone - 多采样渲染到 ios 中的纹理