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

2014-11-24 03:21:36 · 作者: · 浏览: 9
Graphics2D g2d = (Graphics2D) g;

27 float strokeThickness = 5.0f;

28 BasicStroke stroke = new BasicStroke(strokeThickness);

29 g2d.setStroke(stroke);

30 g2d.setColor(Color.blue);

31 g2d.draw(new Rectangle(20, 20, 200, 100));

32 }

33 //绘制带有渐变着色的笔划

34 private void paintGradientStroke(Graphics g) {

35 Graphics2D g2 = (Graphics2D) g;

36 double x = 15, y = getHeight() / 3 + 50, w = 70, h = 70;

37 Ellipse2D e = new Ellipse2D.Double(x, y, w, h);

38 GradientPaint gp = new GradientPaint(75, 75, Color.white, 95, 95, Color.gray, true);

39 // 用渐变着色来填充

40 g2.setPaint(gp);

41 g2.fill(e);

42 // 实心颜色的笔划

43 e.setFrame(x + 100, y, w, h);

44 g2.setPaint(Color.black);

45 g2.setStroke(new BasicStroke(8));

46 g2.draw(e);

47 // 渐变颜色的笔划

48 e.setFrame(x + 200, y, w, h);

49 g2.setPaint(gp);

50 g2.draw(e);

51 }

52 //绘制带有dash模式和线段端头风格的笔划

53 private void paintDashPatternStroke(Graphics g) {

54 Graphics2D g2 = (Graphics2D) g;

55 float dash[] = { 10.0f };

56 //param 1: 笔划的宽度

57 //param 2: 端头样式,他是CAP_BUTT、CAP_ROUND、CAP_SQUARE三种样式中的一个

58 //param 3: 连接样式,他是JOIN_BEVEL、JOIN_MITER和JOIN_ROUND三种样式中的一个

59 //param 4: 用度数表示的角度,如果小于这个角度,斜尖连接将呈现为斜连接

60 //param 5: 虚线笔划的填充部分和空白部分交替出现的一组长度

61 //param 6: 位于笔划起始点前面的这段长度被假设为已经应用了该虚线模式

62 //在该例子中,可以将最后一个参数从0调整到10,以观察显示差异

63 g2.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 3f));

64 g2.setPaint(Color.blue);

65 Rectangle r = new Rectangle(20, getHeight() * 2 / 3 + 20, 200, 100);

66 g2.draw(r);

67 }

68 }

4. 着色:

当填充一个形状的时候,该形状的内部就上了颜色。使用setPaint方法,把颜色的样式设定为一个实现了Paint接口的类的对象。Java 2D API提供了三个这样的类:

1) Color: 实现了Paint接口,使用单色填充形状;

2) GradientPaint: 通过在两个给定的颜色值之间进行渐变,从而改变使用的颜色;

3) TexturePaint: 用一个图像重复的对一个区域进行着色。

1 public class MyTest extends JPanel {

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

3 JFrame f = new JFrame("Paint Demo");

4 f.setSize(600, 600);

5 f.add(new MyTest());

6 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

7 f.setLocationRelativeTo(null);

8 f.setVisible(true);

9 }

10 public MyTest() {

11 setBackground(Color.white);

12 setForeground(Color.white);

13 }

14 @Override

15 public void paintComponent(Graphics g) {

16 super.paintComponent(g);

17 g.setColor(Color.red);

18 g.drawLine(0, getHeight() / 4, getWidth(), getHeight() / 4);

19 g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);

20 g.drawLine(0, getHeight() * 3 / 4, getWidth(), getHeight() * 3 / 4);

21 paintRadialGradient(g);

22 paintGradient(g);

23 paintGradientRectangle(g);

24 paintTexture(g);

25