输出的这幅图像中,一颗精致的金色五角星跃然于深红色背景之上,绽放出迷人的光彩。
要绘画这颗五角星,首先要了解五角星的构造和角度问题。我们可以分为内五边形,和外五边形。内五边形从他的中心到每个外点,连接起来,有五个内角,每个内角是72度。外五边形的五个点,可以看作是内五边形的延长线,所以外五点的连线,每个角是18度。通过计算,再结合正弦定律,内径和外径的比例为sin18和sin126.所以他们的比例是809:309.
开始编程
import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.*;public class DrawStarExample extends JPanel {@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g);int centerX = getWidth() / 2;int centerY = getHeight() / 2;int radius = (int)(centerX*0.9);int outerRadius = (int)(radius*0.809);int innerRadius = (int)(radius * 0.309);int[] xPoints = new int[10];int[] yPoints = new int[10];for (int i = 0; i < 10; i++) {int v = i * 36 ;double angle = Math.toRadians(v);if (i % 2 == 0) {xPoints[i] = (int)(centerX + outerRadius * Math.cos(angle));yPoints[i] = (int)(centerY + outerRadius * Math.sin(angle));} else {xPoints[i] = (int)(centerX + innerRadius * Math.cos(angle));yPoints[i] = (int)(centerY + innerRadius * Math.sin(angle));}}// 绘制五角星g.setColor(Color.yellow);g.fillPolygon(xPoints, yPoints, 10);}public static void main(String[] args) {JFrame frame = new JFrame("我的五角星");DrawStarExample panel = new DrawStarExample();panel.setBackground(Color.red);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.add(panel);frame.setSize(1000, 1000);frame.setLocationRelativeTo(null);frame.setVisible(true);}
输出结果