Graphics2D的应用(绘出旋转的字体)

来源:互联网 发布:饥荒mac版汉化mod 编辑:程序博客网 时间:2024/06/15 19:13
Graphics2D 类扩展了 Graphics 类,提供了对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制。它是用于在 Java(tm) 平台上呈现二维形状、文本和图像的基础类。
下面通过修改画笔的属性来实现文本以一个点为圆心的旋转,不多说看运行后的效果吧。
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. import java.awt.Color;
  6. import java.awt.Dimension;
  7. import java.awt.Font;
  8. import java.awt.Graphics;
  9. import java.awt.Graphics2D;
  10. import javax.swing.JFrame;
  11. import javax.swing.JPanel;
  12. /**
  13.  * 
  14.  * @author huangxf
  15.  */
  16. public class Rotate {
  17.     /**
  18.      * @param args
  19.      */
  20.     public static void main(String[] args) {
  21.         JFrame jf = new JFrame();
  22.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.         jf.getContentPane().add(new RotatePanel());
  24.         jf.setPreferredSize(new Dimension(500400));
  25.         jf.pack();
  26.         jf.setVisible(true);
  27.     }
  28. }
  29. class RotatePanel extends JPanel {
  30.     @Override
  31.     protected void paintComponent(Graphics g) {
  32.         super.paintComponent(g);
  33.         Graphics2D g2d = (Graphics2D) g;
  34.         g2d.setColor(Color.WHITE);
  35.         g2d.fillRect(00this.getWidth(), this.getHeight());
  36.         String s = "Java 2d 旋转";
  37.         Font f = new Font("宋体", Font.BOLD, 16);
  38.         Color[] colors = {Color.ORANGE, Color.LIGHT_GRAY};
  39.         g2d.setFont(f);
  40.         //   平移原点到图形环境的中心
  41.         g2d.translate(this.getWidth() / 2this.getHeight() / 2);
  42.         //   旋转文本
  43.         for (int i = 0; i < 12; i++) {
  44.             g2d.rotate(30 * Math.PI / 180);
  45.             g2d.setPaint(colors[i % 2]);
  46.             g2d.drawString(s, 00);
  47.         }
  48.     }
  49. }



原创粉丝点击