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

2014-11-24 03:21:34 · 作者: · 浏览: 2
neBreakMeasurer基于参数传入的宽度,并结合字体的Metrics,

30 //获取当前行应该渲染的文本布局对象。

31 TextLayout textLayout = lbm.nextLayout(wrappingWidth);

32 //5.2 y + ascent得到的是基线y坐标,并从该点开始绘制本行的文本

33 y += textLayout.getAscent();

34 textLayout.draw(g2, x, y);

35 //5.3 baseline + descent + leading得到下一行的ascent的y坐标

36 y += textLayout.getDescent() + textLayout.getLeading();

37 //5.4 将baseline的x坐标回归到行起点

38 x = insets.left;

39 }

40 }

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

42 JFrame frame = new JFrame();

43 frame.setTitle("Show String with Multiline.");

44 frame.addWindowListener(new WindowAdapter() {

45 public void windowClosing(WindowEvent e) {

46 System.exit(0);

47 }

48 });

49 frame.setContentPane(new MyTest());

50 frame.setSize(800, 500);

51 frame.setVisible(true);

52 }

53 }

10) 一个相对复杂而又步骤清晰的示例代码。

通过该示例,可以更好的理解之前介绍的Java 2D 技巧和本小节的字符绘制知识。

1 public class MyTest extends JPanel {

2 static final int WIDTH = 800, HEIGHT = 375;

3 public void paintComponent(Graphics g) {

4 super.paintComponent(g);

5 Graphics2D g2 = (Graphics2D) g;

6 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING

7 , RenderingHints.VALUE_ANTIALIAS_ON);

8 // 1. 通过渐变绘制整个背景--一个从左上角到右下角的渐变

9 g2.setPaint(new GradientPaint(0, 0, new Color(150, 0, 0)

10 , WIDTH, HEIGHT, new Color(200, 200, 255)));

11 g.fillRect(0, 0, WIDTH, HEIGHT);

12 // 2. 用渐变绘制宽度为15的边框--这里的渐变是通过Alpha值的变化体现出来的。

13 g2.setPaint(new GradientPaint(0, 0, new Color(0, 150, 0), 20, 20

14 , new Color(0, 150, 0, 0), true));

15 g2.setStroke(new BasicStroke(15));

16 g2.drawRect(25, 25, WIDTH - 50, HEIGHT - 50);

17 // 3. 基于Font对象绘制字符,为了显示方便我们需要一个放大的Font

18 Font font = new Font("Serif", Font.BOLD, 10); // a basic font

19 Font bigfont = font.deriveFont(AffineTransform.getScaleInstance(30.0, 30.0));

20 // 4. 基于这个放大的大字体(bigFont)和Graphics2D的字体渲染上下文,

21 // 将字符串"JAV"分解,再基于每个字符的outline生成Shape对象,这样,

22 // Graphics2D就可以想渲染普通形状一样渲染字体信息了。

23 GlyphVector gv = bigfont.createGlyphVector(g2.getFontRenderContext(), "JAV");

24 // 5. jshape 对应J,ashape 对应A,vshape 对应V

25 Shape jshape = gv.getGlyphOutline(0);

26 Shape ashape = gv.getGlyphOutline(1);

27 Shape vshape = gv.getGlyphOutline(2);

28 // 6. 将字体阴影的颜色设置为半透的黑色

29 g2.setStroke(new BasicStroke(5.0f));

30 Paint shadowPaint = new Color(0, 0, 0, 100);

31 // 7. 阴影的光线是斜射的,因此这里需要做切变变化来模拟,再将阴影的Height缩小一倍。

32 AffineTransform shadowTransform = AffineTransform.getShearInstance(-1.0, 0.0);

33 shadowTransform.scale(1.0, 0.5);

34 g2.translate(65, 270);

35 // 8. 设置阴影的背景色

36 g2.setPaint(shadowPaint);

3