“定制”无疑是TWaver中最大的一特色,无论是node,link,attachment,就连tooltip也同样可以定制,“定制”可以显示出更强更复杂的一些功能,今天给大家带来了一个定制Tooltip的例子。
啥也不多说,先看看效果:
下面我们来细细分析一下这个功能的实现。tooltip的特点是当鼠标滑过时显示,滑出时不显示。因此我们可以定义一个tooltip组件,监听network的mouse move事件,如果鼠标下有网元,就显示tooltip组件并动态计算tooltip的位置,没有就隐藏tooltip组件。
this.network.addEventListener(MouseEvent.MOUSE_MOVE, function(e:MouseEvent):void updateToolTip(e); }); private function updateToolTip(e:MouseEvent):void { var element:IElement = network.getElementByMouseEvent(e, true, 5); if(lastElement == element){ return; } lastElement = element; if(element is Link){ var point:Point = network.getLogicalPoint(e); customTooltip.x = point.x - customTooltip.measuredWidth / 2; customTooltip.y = point.y - customTooltip.measuredHeight - 10; customTooltip.setText(element.getClient('message')); customTooltip.visible = true; }else{ customTooltip.visible = false; } }
我们来详细了解一下如何来实现tooltip组件,首先定义一个tooltip类,继承于canvas。这样就可以将tooltip直接加到network.topCanvas上。
public class CustomToolTip extends Canvas {}
tooltip组件上不需要交互动作和滚动条,因此可以将这些屏蔽:
public function CustomToolTip() { this.mouseEnabled = false; this.mouseChildren = false; this.horizontalScrollPolicy = ScrollPolicy.OFF; this.verticalScrollPolicy = ScrollPolicy.OFF; this.init(); }
重点是tooltip的绘制问题,我们需要将图标和文字加到tooltip组件上,并且在添加图标和文字时,需要计算一下位置
var messageImage:Image = new Image(); messageImage.source = new messageIcon(); messageImage.x = _hmargin; messageImage.y = _vmargin; this.addChild(messageImage); _message = new Label(); _message.x = _hmargin + _iconWidth + _hgap; _message.y = _vmargin; this.addChild(_message);
然后我们需要绘制一个如tooltip形状的图形。先来分析一个,tooltip就是一个矩形框,为了好看一点可以搞个圆角矩形,矩形下方有一个小三角的图形。接下来就可以通过画笔将这些图形绘制出来
//获取画笔 var g:Graphics = this.graphics; //设置画笔的线宽为1 var lineWidth:Number = 1; //设置画笔的样式 g.lineStyle(lineWidth, 0, 0.5, true, "normal", CapsStyle.ROUND, JointStyle.ROUND); //设置填充色 Utils.beginFill(g, 0xFFFFFF, 1, 0, 0, _width, _height, Consts.GRADIENT_LINEAR_EAST, 0xCCCCCC, 1); //绘制圆角矩形 g.drawRoundRect(lineWidth, lineWidth, _width - lineWidth * 2, _height - lineWidth * 2 - _arrowHeight, 10, 10); //绘制矩形下的小三角 g.moveTo(_arrowStart, _height - lineWidth - _arrowHeight); g.lineTo(_arrowStart, _height); g.lineTo(_arrowStart + _arrowWidth, _height - lineWidth - _arrowHeight); g.endFill(); //绘制小三角和矩形的连接线的颜色 g.lineStyle(1, 0xFFFFFF); g.moveTo(_arrowStart, _height - lineWidth - _arrowHeight); g.lineTo(_arrowStart + _arrowWidth, _height - lineWidth - _arrowHeight);
这样tooltip就定制好了,最后还需要将网元和tooltip上显示的内容绑定
link.setClient('message', '3333M'); customTooltip.setText(element.getClient('message'));
原文出处和原代码请参见这里。