21xrx.com
2024-11-22 11:42:45 Friday
登录
文章检索 我的文章 写文章
Java 绘制五彩星星闪烁的代码
2023-06-14 21:41:36 深夜i     --     --
Java Graphics2D 绘图

在 Java 中,我们可以利用 Graphics2D 绘图工具类来绘制五彩闪烁的星星效果。下面是代码实现:


import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class StarDraw extends JPanel {

  @Override

  public void paint(Graphics g) {

    super.paint(g);

    Graphics2D g2d = (Graphics2D)g;

    

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

        RenderingHints.VALUE_ANTIALIAS_ON);

    

    for (int i = 1; i <= 5; i++) {

      int x = (int)(Math.random() * (getWidth() - 50));

      int y = (int)(Math.random() * (getHeight() - 50));

      Star star = new Star(x, y, 50, 30, 5, Color.WHITE, Color.getHSBColor((float)Math.random(), 1, 1));

      star.draw(g2d);

    }

    

  }

  

  public static void main(String[] args) {

    JFrame frame = new JFrame("Draw Star");

    frame.add(new StarDraw());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(new Dimension(500, 500));

    frame.setLocationRelativeTo(null);

    frame.setVisible(true);

  }

}

class Star {

  private int x, y, rOuter, rInner, nPoints;

  private Color cInner, cOuter;

  

  public Star(int x, int y, int rOuter, int rInner, int nPoints, Color cOuter, Color cInner)

    this.x = x;

    this.y = y;

    this.rOuter = rOuter;

    this.rInner = rInner;

    this.nPoints = nPoints;

    this.cOuter = cOuter;

    this.cInner = cInner;

  

  

  public void draw(Graphics2D g2d) {

    int[] xOuter = new int[nPoints];

    int[] yOuter = new int[nPoints];

    int[] xInner = new int[nPoints];

    int[] yInner = new int[nPoints];

    

    double deltaAngle = Math.PI / nPoints;

    for (int i = 0; i < nPoints; i++) {

      double angle = deltaAngle + i * 2 * deltaAngle;

      int x = (int)(rOuter * Math.sin(angle));

      int y = (int)(rOuter * Math.cos(angle));

      xOuter[i] = this.x + x;

      yOuter[i] = this.y - y;

      

      x = (int)(rInner * Math.sin(angle + deltaAngle));

      y = (int)(rInner * Math.cos(angle + deltaAngle));

      xInner[i] = this.x + x;

      yInner[i] = this.y - y;

    }

    

    g2d.setColor(cOuter);

    g2d.fillPolygon(xOuter, yOuter, nPoints);

    

    g2d.setColor(cInner);

    g2d.fillPolygon(xInner, yInner, nPoints);

    

  }

}

运行代码,可以看到窗口中绘制了 5 个五边形的星星,并且每个星星的颜色都是随机的,并且在窗口中不停的闪烁着。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复