java实现绘制跳动的桃心(附完整源码)
时间: 2023-11-12 21:05:02 浏览: 128
下面是Java实现绘制跳动的桃心的完整源码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class BeatingHeart extends JPanel {
private int time = 0;
public BeatingHeart() {
setPreferredSize(new Dimension(500, 500));
setBackground(Color.white);
Timer timer = new Timer(50, e -> {
time++;
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int size = Math.min(getWidth(), getHeight()) / 4;
double angle = time * 0.04;
double x = size * (16 * Math.pow(Math.sin(angle), 3));
double y = -size * (13 * Math.cos(angle) - 5 * Math.cos(2 * angle) - 2 * Math.cos(3 * angle) - Math.cos(4 * angle));
GeneralPath heart = new GeneralPath();
heart.moveTo(centerX + x, centerY + y);
heart.curveTo(centerX + x, centerY + y - size / 2, centerX + x - size, centerY + y - size / 2, centerX + x - size, centerY + y);
heart.curveTo(centerX + x - size, centerY + y + size / 2, centerX + x, centerY + y + size / 8, centerX + x, centerY + y + size / 2);
heart.closePath();
g2d.setColor(Color.red);
g2d.fill(heart);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Beating Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BeatingHeart());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
使用方法:
直接运行main方法即可看到跳动的桃心。
这里使用了Java2D图形库,通过绘制GeneralPath来实现桃心的绘制。桃心的形状采用了三次贝塞尔曲线来构造,其中心位置和大小随时间变化,实现了桃心跳动的效果。
阅读全文