想想Java2D中给我们提供的线的样式着实很少,除了直线,虚线,好像就没有其他的什么样式了,如果细心的童鞋还会发现,TWaver中倒是提供了一种比较特殊的连线,波浪曲折式的连线。

这种波浪曲折的连线如果让我们自己来实现也是有多种实现的方式,还记得之前几篇文章中定制过的LinkUI么,也是各式各样的方式,比如:
五彩斑斓的Link

流动点式的Link

今天给大家介绍的是箭头流动式的Link,何为箭头流动,我们就先来看看效果图:

这是一个从from节点流向to节点的连线,连线是以一个一个箭头组建而成,这样的连线方式看上去比传统的那种流动漂亮多了,也有不少客户提及到这种样式。本篇我将详细给大家讲解一下实现的细节。
首先需要定制一个ArrowLink继承于Link,在ArrowLink中需要给它定义几个变量,例如:线的宽度、颜色、每段箭头的长度、需要填充的流动箭头的数量、透明度、是否是从from流向to以及偏移(用于显示流动)等等。 不说这么多了,直接看代码:
1 public class ArrowLink extends Link {
2
3 public ArrowLink() {
4 super();
5 init();
6 }
7
8 public ArrowLink(Object id) {
9 super(id);
10 init();
11 }
12
13 public ArrowLink(Node from, Node to) {
14 super(from, to);
15 init();
16 }
17
18 public ArrowLink(Object id, Node from, Node to) {
19 super(id, from, to);
20 init();
21 }
22
23 private void init() {
24 this.putLinkColor(new Color(0, 0, 0, 0));
25 this.putLinkOutlineWidth(0);
26 this.setLinkType(TWaverConst.LINK_TYPE_PARALLEL);
27 this.putLinkAntialias(true);
28 this.putClientProperty("lineWidth", 3.0f);
29 this.putClientProperty("lineColor", Color.blue);
30 this.putClientProperty("offset", 0.0);
31 this.putClientProperty("segmentLength", 8.0);
32 this.putClientProperty("fillSegmentCount", 5);
33 this.putClientProperty("defaultAlpha", 0.2);
34 this.putClientProperty("from", true);
35 }
36
37 public String getUIClassID() {
38 return ArrowLinkUI.class.getName();
39 }
40
41 }
定制完连线之后,最主要的是需要重画LinkUI,自定义ArrowLinkUI类继承于LinkUI并重载paintBody方法,paintBody中我们需要画出一个一个的箭头,箭头实现起来其实还是比较简单的,我们能获取Link的长度并且知道Link上每段的长度,就可以计算出需要绘制箭头的数量。
1 int count = (int)(length/segmentLength);
根据箭头的数量可以获取到需要绘制箭头的每个点的位置:
1 List points = TWaverUtil.divideShape(this.path, count);
获取到这个位置之后,我们就可以以这个点为中心点,分别计算出箭头的其他两个点的位置:
1 Point2D p0 = new Point.Double();
2 transform.transform(point, p0);
3 Point2D p1 = new Point.Double();
4 transform.transform(new Point.Double(point.getX() + segmentLength/2 * sign, point.getY() - segmentLength/2), p1);
5 Point2D p2 = new Point.Double();
6 transform.transform(new Point.Double(point.getX() + segmentLength/2 * sign, point.getY() + segmentLength/2), p2);
这样一个箭头就可以绘制出来了

其他的箭头也可以以同样方式循环绘制出来,需要注意的是箭头是需要随着node的位置旋转的,因此我们需要计算出箭头旋转的角度和旋转点的位置:
1 AffineTransform transform = new AffineTransform();
2 transform.translate(point.getX(), point.getY());
3 transform.rotate(angle);
4 transform.translate(-point.getX(), -point.getY());
最后还有流动的效果,这里我们设置了一个offset的参数,可以表示流动的偏移量,根据偏移量以及填充的流动箭头的数量来确定当前这个箭头的透明度:
1 double alpha = (Double)this.element.getClientProperty("defaultAlpha");
2 if(offset * count >= i && offset * count - fillSegmentCount <= i){
3 alpha = 1 - (offset * count - i)/fillSegmentCount * 0.5;
4 }
完整绘制箭头的代码如下:
1 public class ArrowLinkUI extends LinkUI {
2
3 public ArrowLinkUI(TNetwork network, Link link) {
4 super(network, link);
5 }
6
7 public void paintBody(Graphics2D g2d) {
8 super.paintBody(g2d);
9 this.drawFlowing(g2d);
10 }
11
12 private void drawFlowing(Graphics2D g2d) {
13 double length = TWaverUtil.getLength(this.path);
14 if(length < =0 ){
15