今天有幸碰到關(guān)于Connection以及Router使用的問題。覺得有點(diǎn)意思就把它記了下來。以背后查。
看到一個(gè)例子中看到圖
-- 1所示的功能。
其中圖-1中的連線是自適應(yīng)的會(huì)保持該線段是最短的(其實(shí)他是使用的ShortestPathConnectionRouter,這個(gè)時(shí)候我還不知道,我是一個(gè)新手大家見笑了)。經(jīng)過一番調(diào)查以后發(fā)現(xiàn)原來是在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);
????????}
當(dāng)時(shí)就猜啊,他肯定是在給一個(gè)特定的Layer加上一個(gè)什么玩意。然后就通過這個(gè)玩意來完成對(duì)于路徑的計(jì)算(其實(shí)這些東西完全是從代碼的字面意思而得到的)。我這些東西加到我的代碼中了。但是我運(yùn)行的效果還是沒有起作用。他依舊是以前的那幅得行。我抓,抓也沒有用。就是達(dá)不到我要的效果。
抱著試一下的想法我打開了我的ConnectionEditPart(就是連線的那個(gè)EditPart),發(fā)現(xiàn)在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賦了一個(gè)ConnectionRouter。最終其效果的是這一個(gè)ConnectionRouter起作用了。
Md剛掉他就萬事大吉了。
到這里代碼部分其實(shí)就完了。但是他背后的還有一點(diǎn)故事。
這里有三個(gè)角色:
1、Connection
2、ConnectionAnchor.
3
、
ConnectionRouter
這個(gè)類是用來顯示兩點(diǎn)之間的線段
(Line),
他的起點(diǎn)和終點(diǎn)是通過
ConnectionAnchor
來定義的。至于他的其他點(diǎn)是通過
ConnectionRouter
計(jì)算設(shè)置的。從這個(gè)地方來看
ConnectionRouter
是一個(gè)負(fù)責(zé)計(jì)算的工具類。這樣完全可以讓所有的
Connection
使用一個(gè)
ConnectionRouter
實(shí)例(這就是今天最要記下的部分)。
在
gef
中他就為我們提供了這樣的機(jī)制。下面的這段話是
Gef
help
中的一句話。他就說明了這個(gè)道理。
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.
這個(gè)道理要轉(zhuǎn)換成代碼的話就是代碼
–
1
了。
這個(gè)東西很簡(jiǎn)單。希望對(duì)像我一樣的新手有點(diǎn)幫助。