Java画一个爱心

用到的公式

代码

package middleExam;

import javax.swing.*;
import java.awt.*;

/**
 * @author WuYongheng
 * @date 2022/11/10
 * @description
 */
public class love extends JFrame {
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    private static int WINDOW_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
    private static int WINDOW_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;

    public love() {
        super("I love you");//设置窗口标题
        this.setBackground(Color.BLACK);
        this.setLocation((WINDOW_WIDTH - WIDTH) / 2, (WINDOW_HEIGHT - HEIGHT) / 2);//设置窗口位置
        this.setSize(WIDTH, HEIGHT);//设置窗口大小
        this.setLayout(getLayout());//设置窗口布局
        this.setVisible(true);//设置窗口可见
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);//设置窗口默认关闭方式
    }

    public void paint(Graphics g) {
        double x, y; //横纵坐标
        double rx, ry;
        Image image = this.createImage(WIDTH, HEIGHT);
        Graphics pic = image.getGraphics();
        for (int t = 0; t < 90; t++) {
            x = 16 * Math.pow(Math.sin(Math.PI / 45 * t), 3);
            // 先放大,再移动到画布中央
            x = x * 11;
            x = x + WIDTH / 2;
            y = -(13 * Math.cos(Math.PI / 45 * t) - 5 * Math.cos(Math.PI / 45 * 2 * t)
                    - 2 * Math.cos(Math.PI / 45 * 3 * t) - Math.cos(Math.PI / 45 * 4 * t));
            y = y * 11;
            y = y + HEIGHT / 2;
            /**
             * 使用随机数达到散射粒子效果
             */
            for (int i = 0; i < 10; i++) {
                double r = Math.random();
                rx = (0.15) * Math.log(r);
                ry = (0.15) * Math.log(r);
                double dx = rx * (x - WIDTH / 2);
                double dy = ry * (y - HEIGHT / 2);
                pic.setColor(Color.pink);
                pic.fillOval((int) (x - dx), (int) (y - dy), 2, 2);
            }
            pic.setColor(Color.red);
            pic.fillOval((int) x, (int) y, 2, 2);
        }
        g.drawImage(image, 0, 0, this);//生成图片
    }
    public static void main(String[] args) {
        new love();
    }
}

 效果:

猜你喜欢

转载自blog.csdn.net/Ipkiss_Yongheng/article/details/127794935