帮我用java写一个心形
时间: 2024-01-05 11:04:50 浏览: 32
以下是使用Java Swing绘制心形的示例代码:
```
import java.awt.*;
import javax.swing.*;
public class HeartShape extends JPanel {
private static final long serialVersionUID = 1L;
public HeartShape() {
setPreferredSize(new Dimension(300, 300));
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = 80;
int x1 = centerX - radius;
int y1 = centerY;
int x2 = centerX + radius;
int y2 = centerY;
int x3 = centerX;
int y3 = centerY + radius;
int x4 = centerX;
int y4 = centerY - radius;
int controlX1 = x1 + (x2 - x1) / 3;
int controlY1 = y1 - radius / 2;
int controlX2 = x1 + (x2 - x1) * 2 / 3;
int controlY2 = controlY1;
int controlX3 = centerX;
int controlY3 = y4 + radius / 2;
int controlX4 = x2 - (x2 - x1) / 3;
int controlY4 = controlY3;
g2d.setStroke(new BasicStroke(2));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawArc(x1, y1 - radius / 2, 2 * radius, 2 * radius, 0, -180);
g2d.drawArc(x2 - radius, y2 - radius / 2, 2 * radius, 2 * radius, 0, -180);
g2d.curveTo(controlX4, controlY4, controlX3, controlY3, x3, y3);
g2d.curveTo(controlX1, controlY1, controlX2, controlY2, x4, y4);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Shape");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HeartShape());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
该代码使用了Java Swing中的JPanel类进行绘图,并重写了paintComponent方法来实现心形的绘制。运行该代码可以看到一个红色的心形图案。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)