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

2014-11-24 03:21:36 · 作者: · 浏览: 1
}

26 // 绘制放射性渐变 www.2cto.com

27 private void paintRadialGradient(Graphics g) {

28 Graphics2D g2 = (Graphics2D) g;

29 double radius = getWidth() / (2 * 4);

30 Paint p = new RadialGradientPaint(new Point2D.Double(radius, radius),

31 (float) radius, new float[] { 0.0f, 1.0f }, new Color[] {

32 new Color(6, 76, 160, 127),

33 new Color(0.0f, 0.0f, 0.0f, 0.8f) });

34 g2.setPaint(p);

35 g2.fillOval(0, 0, (int) radius * 2 - 10, (int) radius * 2 - 10);

36 }

37 // 绘制普通渐变

38 private void paintGradient(Graphics g) {

39 Paint paint = new GradientPaint(0, getHeight() / 4, Color.red,

40 (float) getWidth() / 4, (float) getHeight() / 2, Color.blue);

41 Graphics2D g2 = (Graphics2D) g;

42 g2.setPaint(paint);

43 Ellipse2D circle = new Ellipse2D.Double(0, getHeight() * 0.25,

44 getWidth() / 4 - 5, getHeight() / 4 - 5);

45 g2.fill(circle);

46 }

47 // Color的填充

48 private void paintGradientRectangle(Graphics g) {

49 Graphics2D g2 = (Graphics2D) g;

50 Dimension d = getSize();

51 // 将坐标移动到中心

52 g2.translate(d.width / 2, d.height * 5 / 8);

53 Color[] colors = { Color.white, Color.lightGray, Color.gray,

54 Color.darkGray, Color.black, Color.red, Color.pink,

55 Color.orange, Color.yellow, Color.green, Color.magenta,

56 Color.cyan, Color.blue };

57

58 float size = 25;

59 float x = -size * colors.length / 2;

60 float y = -size * 3 / 2;

61

62 // 在第一行显示预定义的颜色

63 for (int i = 0; i < colors.length; i++) {

64 Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y,

65 size, size);

66 g2.setPaint(colors[i]);

67 g2.fill(r);

68 }

69 // 显示一个手工计算的线性渐变

70 y += size;

71 Color c1 = Color.yellow;

72 Color c2 = Color.blue;

73 for (int i = 0; i < colors.length; i++) {

74 float ratio = (float) i / (float) colors.length;

75 int red = (int) (c2.getRed() * ratio + c1.getRed() * (1 - ratio));

76 int green = (int) (c2.getGreen() * ratio + c1.getGreen()

77 * (1 - ratio));

78 int blue = (int) (c2.getBlue() * ratio + c1.getBlue() * (1 - ratio));

79 Color c = new Color(red, green, blue);

80 Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y,

81 size, size);

82 g2.setPaint(c);

83 g2.fill(r);

84 }

85 // 显示一个手工计算透明度的线性渐变

86 y += size;

87 c1 = Color.red;

88 for (int i = 0; i < colors.length; i++) {

89 int alpha = (int) (255 * (float) i / (float) colors.length);

90 Color c = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), alpha);

91 Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y,

92