今天有幸碰到關于Connection以及Router使用的問題。覺得有點意思就把它記了下來。以背后查。
看到一個例子中看到圖
-- 1所示的功能。
其中圖-1中的連線是自適應的會保持該線段是最短的(其實他是使用的ShortestPathConnectionRouter,這個時候我還不知道,我是一個新手大家見笑了)。經過一番調查以后發現原來是在EditPart中的refreshVisuals方法中有如下代碼。
代碼--1
if
?(spRouter?
==
?
null
)?{
????????????ConnectionLayer?cLayer?
=
?(ConnectionLayer)?getLayer(LayerConstants.CONNECTION_LAYER);
????????????FanRouter?router?
=
?
new
?FanRouter();
????????????router.setSeparation(
30
);
????????????spRouter?
=
?
new
?ShortestPathConnectionRouter(getFigure());
????????????router.setNextRouter(spRouter);
????????????cLayer.setConnectionRouter(router);
????????}
當時就猜啊,他肯定是在給一個特定的Layer加上一個什么玩意。然后就通過這個玩意來完成對于路徑的計算(其實這些東西完全是從代碼的字面意思而得到的)。我這些東西加到我的代碼中了。但是我運行的效果還是沒有起作用。他依舊是以前的那幅得行。我抓,抓也沒有用。就是達不到我要的效果。
抱著試一下的想法我打開了我的ConnectionEditPart(就是連線的那個EditPart),發現在createFigure中我是這么寫的。
代碼 --
2
PolylineConnection?connection?
=
?(PolylineConnection)
super
.createFigure();
???????
????????connection.setConnectionRouter(
new
?BendpointConnectionRouter(){
????????????
public
?
void
?route(Connection?conn)?{
????????????????GraphAnimation.recordInitialState(conn);
????????????????
if
?(
!
GraphAnimation.playbackState(conn))
????????????????????
super
.route(conn);
????????????}
????????});
很明顯我在這里給connection賦了一個ConnectionRouter。最終其效果的是這一個ConnectionRouter起作用了。
Md剛掉他就萬事大吉了。
到這里代碼部分其實就完了。但是他背后的還有一點故事。
這里有三個角色:
1、Connection
2、ConnectionAnchor.
3
、
ConnectionRouter
這個類是用來顯示兩點之間的線段
(Line),
他的起點和終點是通過
ConnectionAnchor
來定義的。至于他的其他點是通過
ConnectionRouter
計算設置的。從這個地方來看
ConnectionRouter
是一個負責計算的工具類。這樣完全可以讓所有的
Connection
使用一個
ConnectionRouter
實例(這就是今天最要記下的部分)。
在
gef
中他就為我們提供了這樣的機制。下面的這段話是
Gef
help
中的一句話。他就說明了這個道理。
A
convenient way to share the router with all connections and to place
connections above the drawing is to use a ConnectionLayer
.
The layer has a connection router property which it shares with every
child that's a connection. You can update this property and easily
change every connection's router at once.
這個道理要轉換成代碼的話就是代碼
–
1
了。
這個東西很簡單。希望對像我一樣的新手有點幫助。