Step By Step(Java 2D图形篇<四>) (四)

2014-11-24 03:21:34 · 作者: · 浏览: 3
Graphics2D g2 = (Graphics2D) g;

9 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING

10 , RenderingHints.VALUE_ANTIALIAS_ON);

11 //1. 根据字体、字符串和Graphics的字体渲染上下文对象获取文本布局对象

12 TextLayout textTl = new TextLayout(s, f, g2.getFontRenderContext());

13 //2. 通过文本布局对象取得字符串的outline(以Shape的方式获得)

14 Shape outline = textTl.getOutline(null);

15 //3. 获取字符串图形对象outline的边界矩形

16 Rectangle outlineBounds = outline.getBounds();

17 //4. 像绘制其他普通形状一样绘制outline

18 AffineTransform transform = new AffineTransform();

19 transform = g2.getTransform();

20 transform.translate(width / 2 - (outlineBounds.width / 2),

21 height / 2 + (outlineBounds.height / 2));

22 g2.transform(transform);

23 g2.setColor(Color.blue);

24 g2.draw(outline);

25 g2.setClip(outline);

26 }

27 public static void main(String[] args) {

28 JFrame frame = new JFrame();

29 frame.setTitle("Load TTF From File");

30 frame.addWindowListener(new WindowAdapter() {

31 public void windowClosing(WindowEvent e) {

32 System.exit(0);

33 }

34 });

35 frame.setContentPane(new MyTest());

36 frame.setSize(600, 400);

37 frame.setVisible(true);

38 }

39 }

6) 通过TextAttribute设置字体的属性,如下划线、背景色和前景色等:

1 public class MyTest extends JPanel {

2 public void paintComponent(Graphics g) {

3 super.paintComponent(g);

4 Graphics2D g2 = (Graphics2D) g;

5 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

6 Font font = new Font("Serif", Font.PLAIN, 40);

7 AttributedString as1 = new AttributedString("1234567890");

8 as1.addAttribute(TextAttribute.FONT, font);

9 g2.drawString(as1.getIterator(), 15, 60);

10 //通过最后两个参数可以给字符串中的子字符串添加属性,如果不指定则应用于所有字符。

11 //加下划线

12 as1.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON,3,4);

13 g2.drawString(as1.getIterator(), 15, 120);

14 //加背景色

15 as1.addAttribute(TextAttribute.BACKGROUND, Color.LIGHT_GRAY);

16 g2.drawString(as1.getIterator(), 15, 180);

17 //加横线

18 as1.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);

19 g2.drawString(as1.getIterator(), 15, 240);

20 //加前景色

21 as1.addAttribute(TextAttribute.FOREGROUND, Color.red);

22 g2.drawString(as1.getIterator(), 15, 300);

23 }

24 public static void main(String[] args) {

25 JFrame frame = new JFrame();

26 frame.setTitle("Set Font Attribute with TextAttribute");

27 frame.addWindowListener(new WindowAdapter() {

28 public void windowClosing(WindowEvent e) {

29 System.exit(0);

30 }

31 });

32 frame.setContentPane(new MyTest());

33 frame.setSize(800, 500);

34 frame.setVisible(true);

35 }

36 }

7) 字体属性(FontMe