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

2014-11-24 03:21:34 · 作者: · 浏览: 7
trics)的常用参量:

Baseline: 字体的基线,如g.drawString("Hello",x,BaselineY)

getAscent(): 字体的上差值,在所有的数字和字符中,其最高点到基线的距离

getDescent(): 字体的下差值,在所有的数字和字符中,其最低点到基线的距离

getLeading(): 当前行的Descend到下一行Ascend之间的距离

getHeigth(): 字体的高度= Ascent + Descent + Leading.

下面的示例代码在运行后,可以显示的给出各个参量所表示的具体范围。

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

6 , RenderingHints.VALUE_ANTIALIAS_ON);

7 g2.setFont(new Font("SansSerif", 0, 200));

8 FontMetrics fm = g2.getFontMetrics();

9 int baseline = 300;

10 g2.drawString("By", 200,baseline);

11 g2.setColor(Color.red);

12 g2.setFont(new Font("SansSerif", 0, 15));

13 //可以看出Height = Ascent + Descent + Leading

14 int ascent = fm.getAscent();

15 int descent = fm.getDescent();

16 int leading = fm.getLeading();

17 int height = fm.getHeight();

18 System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d"

19 ,height,ascent,descent,leading);

20 //在文字上绘制每一个常量,用一条横线予以标注

21 g2.drawLine(100, baseline, 500, baseline);

22 g2.drawLine(100, baseline - ascent, 500, baseline - ascent);

23 g2.drawLine(100, baseline + descent, 500, baseline + descent);

24 g2.drawLine(100, baseline - ascent - leading, 500, baseline - ascent - leading);

25 //指出基线的位置,和其他常量作用的范围。

26 g2.drawString("Baseline",510,baseline);

27 g2.drawLine(480, baseline - ascent, 480, baseline);

28 //绘出Ascent的范围

29 g2.drawString("Ascent", 510, baseline - ascent/2);

30 g2.drawLine(480, baseline, 480, baseline + descent);

31 //绘出Descent的范围

32 g2.drawString("Descent", 510, baseline + descent/2);

33 //绘出Leading的范围

34 g2.drawLine(480, baseline - ascent, 480, baseline - ascent - leading);

35 g2.drawString("Leading", 510, baseline - ascent - leading/2);

36 //绘出Height的范围

37 g2.drawLine(100,baseline - ascent - leading,100, baseline + descent);

38 g2.drawString("Height", 30, baseline - ascent - leading + height/2);

39 }

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

41 JFrame frame = new JFrame();

42 frame.setTitle("Show Font's Metrics Info");

43 frame.addWindowListener(new WindowAdapter() {

44 public void windowClosing(WindowEvent e) {

45 System.exit(0);

46 }

47 });

48 frame.setContentPane(new MyTest());

49 frame.setSize(800, 500);

50 frame.setVisible(true);

51 }

52 }

8) 通过FontMetrics获取单个字符在指定字体上的宽度和高度,再逐个绘制每个字符。

1 public class MyTest extends JPanel {

2 public void paintComponent(Graphics g) {

3 super.paintComponent(g);

4 Graphics2D g2 = (Graphics2D) g;

5 g2.setRende