JAVA中的圆周运动图像

时间:2011-10-13 10:23:45

标签: java animation

我想在JAVA中进行图像的圆周运动,我认为我有解决方案,但它不起作用,我现在有点无能为力。

为了计算积分需要用毕达哥拉斯来计算高度(B点)。

如果它确实满足一轮,但更多的轮次会很酷。

图像尺寸约为500 x 300像素。

这是我的代码:

package vogel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class Vogel extends Component {
    private int x;
    private int r;
    private int b;
    BufferedImage img;

    public vogel() {
       try {
           img = ImageIO.read(new File("F:/JAVA/workspace/School/src/vogel/vogel.png"));
       } catch (IOException e) {
       } 
       r = 60;
       x = 10;
    }

    @Override
    public void paint(Graphics g) {
        for(int i = -x; i <= x; i++) {      
            b = (int)Math.sqrt(r^2 - i^2);
            g.drawImage(img, x, b, this);
        }        
    }

    public static void main(String[] args) { 
    JFrame f = new JFrame("Vogel");   
    f.setSize(1000,1000);
    f.add(new Vogel());        
    f.setVisible(true);

    for (int number = 1; number <= 1500000; number++) {
        f.repaint();

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {}
        }
    }
}

2 个答案:

答案 0 :(得分:2)

在paint(Graphics)方法中使用你的循环,它会绘制21只鸟并重新绘制一次。

您应该使用存储在对象变量中的角度来执行此操作,并使用Math.sin()和Math.cos()函数计算x和y位置。每个重绘()都应该增加角度。

添加:

// To control the radius of moving
private final double MAX_X = 200;
private final double MAX_Y = 200;

private double angle = 0;

@Override
public void paint(Graphics g) {
    // increase angle (should be a double value)
    angle += 0.1;

    // rotate around P(0/0), assuming that 0° is vector (1/0)
    int x = (int) (Math.cos(angle) * MAX_X);
    int y = (int) (Math.sin(angle) * MAX_Y);

    // move P to center of JFrame (width and height = 1000)
    x += 500;
    y += 500;

    // image is 500x300, calc upper left corner
    x -= 250;
    y -= 150;

    // draw
    g.drawImage(img, x, y, null);
}

删除:

private double x, b, r;

所以这是代码,试试吧。

答案 1 :(得分:1)

添加Sibbo的代码以将角度转换为rads

private double angle = 0.1;

@Override
public void paint(Graphics g) {
    // increase angle (should be a double value

    double random = angle * 2.0 * Math.PI/360.0; //this will convert it to rads
    // rotate around P(0/0)
    int x = (int) (Math.cos(random) * MAX_X);
    int y = (int) (Math.sin(random) * MAX_Y);

    // move P to center of JFrame (width and height = 1000)
    x += 500;
    y += 500;

    // image is 500x300, calc upper left corner
    x -= 250;
    y -= 150;
    angle++
    // draw
    g.drawImage(img, x, y, null);
}