21xrx.com
2024-11-05 18:46:12 Tuesday
登录
文章检索 我的文章 写文章
Java代码教你创建爱心图案
2023-06-17 00:58:06 深夜i     --     --
Java代码 爱心图案 Graphics2D

想要在Java中创建一个美丽的爱心图案,不仅需要学习一些基本的编程技巧,还需要一定的创意和设计感。本文将为大家详细介绍如何使用Java代码输出一个漂亮的爱心图案。

首先,我们需要使用Java Graphics2D类库,通过绘制两个相互交错的圆形来创建半个心形。具体操作可以参考以下代码:


public void paintComponent(Graphics g) {

  super.paintComponent(g);

  

  Graphics2D g2d = (Graphics2D) g;

  

  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

      RenderingHints.VALUE_ANTIALIAS_ON);

  g2d.setStroke(new BasicStroke(1));

  

  g2d.setColor(Color.RED);

  g2d.fillOval(75, 30, 100, 100);

  g2d.fillOval(175, 30, 100, 100);

  

  g2d.setColor(Color.PINK);

  CubicCurve2D c = new CubicCurve2D.Double();

  c.setCurve(75, 130, 60 ,170, 130, 180, 150, 120);

  g2d.draw(c);

  

  CubicCurve2D c2 = new CubicCurve2D.Double();

  c2.setCurve(150, 120, 170, 180, 240, 170, 225, 130);

  g2d.draw(c2);

}

完成这个半个心形之后,我们再将它沿着对称轴翻转一下,并合并在一起。具体的代码如下:


public void paintComponent(Graphics g) {

  super.paintComponent(g);

  

  Graphics2D g2d = (Graphics2D) g;

  

  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

      RenderingHints.VALUE_ANTIALIAS_ON);

  g2d.setStroke(new BasicStroke(1));

  

  g2d.setColor(Color.RED);

  g2d.fillOval(75, 30, 100, 100);

  g2d.fillOval(175, 30, 100, 100);

  

  g2d.setColor(Color.PINK);

  CubicCurve2D c = new CubicCurve2D.Double();

  c.setCurve(75, 130, 60 ,170, 130, 180, 150, 120);

  g2d.draw(c);

  

  CubicCurve2D c2 = new CubicCurve2D.Double();

  c2.setCurve(150, 120, 170, 180, 240, 170, 225, 130);

  g2d.draw(c2);

  

  AffineTransform transform = new AffineTransform();

  transform.rotate(Math.toRadians(180), 150, 100);

  Shape heart = transform.createTransformedShape(c);

  

  GeneralPath path = new GeneralPath();

  path.append(c2, false);

  path.append(heart, false);

  

  g2d.fill(path);

}

现在,我们就可以通过调用drawHeart函数来输出我们刚才创建的爱心图案了。如下所示:


public void drawHeart(Graphics g) {

  Graphics2D g2d = (Graphics2D) g;

  

  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

      RenderingHints.VALUE_ANTIALIAS_ON);

  g2d.setStroke(new BasicStroke(1));

  

  g2d.setColor(Color.RED);

  g2d.fillOval(75, 30, 100, 100);

  g2d.fillOval(175, 30, 100, 100);

  

  g2d.setColor(Color.PINK);

  CubicCurve2D c = new CubicCurve2D.Double();

  c.setCurve(75, 130, 60 ,170, 130, 180, 150, 120);

  g2d.draw(c);

  

  CubicCurve2D c2 = new CubicCurve2D.Double();

  c2.setCurve(150, 120, 170, 180, 240, 170, 225, 130);

  g2d.draw(c2);

  

  AffineTransform transform = new AffineTransform();

  transform.rotate(Math.toRadians(180), 150, 100);

  Shape heart = transform.createTransformedShape(c);

  

  GeneralPath path = new GeneralPath();

  path.append(c2, false);

  path.append(heart, false);

  

  g2d.fill(path);

}

到这里,我们就成功地完成了Java代码输出爱心的过程。可以根据自己的需求进行代码修改,创建出各种款式的爱心图案。

  
  
下一篇: 的用法及区别

评论区

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