java生成一个动态爱心
时间: 2024-05-10 22:19:10 浏览: 90
java代码实现动态爱心代码示例
以下是Java生成动态爱心的代码,使用了Java Swing库:
```java
import javax.swing.*;
import java.awt.*;
public class DynamicHeart extends JFrame {
private static final int WIDTH = 600;
private static final int HEIGHT = 600;
public DynamicHeart() {
setTitle("Dynamic Heart");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.RED);
int x0 = WIDTH / 2;
int y0 = HEIGHT / 2;
int r = 150;
double angle = 0;
double dAngle = Math.PI / 180;
while (angle < 2 * Math.PI) {
int x = (int) (x0 + r * (16 * Math.pow(Math.sin(angle), 3)));
int y = (int) (y0 - r * (13 * Math.cos(angle) - 5 * Math.cos(2 * angle) - 2 * Math.cos(3 * angle) - Math.cos(4 * angle)));
g2d.drawLine(x0, y0, x, y);
angle += dAngle;
}
}
public static void main(String[] args) {
new DynamicHeart();
}
}
```
代码中使用了心形曲线方程,通过Graphics2D类的drawLine()方法连接每个点,形成了一个动态的爱心。运行代码即可看到动态爱心效果。
阅读全文