有关GEF中Anchor的知识请参阅http://xyhsm.javaeye.com/blog/67809。
原理是根据目标图形在源图形的相对位置(上下左右),并以45度角为分割,决定Anchor具体在四个边框中具体那一个的中部。
import
org.eclipse.draw2d.AbstractConnectionAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
/** */ /**
* A anchor at border's middle for joining connections between figures
* @author wu_07
*/
public class BorderMiddleAnchor extends AbstractConnectionAnchor
... {
private int offset;
public BorderMiddleAnchor(IFigure source)
...{
super(source);
}
public Point getLocation(Point reference)
...{
Rectangle r = getOwner().getBounds().getCopy();
getOwner().translateToAbsolute(r);
int off_h = r.height / 2;
int off_w = r.width / 2;
double vert=r.y-reference.y;
double hort=r.x-reference.x;
/**//* System.out.println("reference.x:"+reference.x);
System.out.println("r.x:"+r.x);
System.out.println("reference.y:"+reference.y);
System.out.println("r.y:"+r.y);
System.out.println("vert:"+vert);
System.out.println("hort:"+hort); */
if (hort<0&&(vert/hort<1&&vert/hort>-1)) //左侧
return r.getTopRight().translate( 0,off_h);
else if (vert>0&&(hort/vert<1&&hort/vert>-1))//下侧
return r.getTopLeft().translate(off_w, 0);
else if (hort>0&&(vert/hort<1&&vert/hort>-1))//右侧
return r.getTopLeft().translate(-1,off_h);
else if (vert<0&&(hort/vert<1&&hort/vert>-1))//上侧
return r.getBottomLeft().translate(off_w, 0);
else
return r.getCenter();
}
}
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
/** */ /**
* A anchor at border's middle for joining connections between figures
* @author wu_07
*/
public class BorderMiddleAnchor extends AbstractConnectionAnchor
... {
private int offset;
public BorderMiddleAnchor(IFigure source)
...{
super(source);
}
public Point getLocation(Point reference)
...{
Rectangle r = getOwner().getBounds().getCopy();
getOwner().translateToAbsolute(r);
int off_h = r.height / 2;
int off_w = r.width / 2;
double vert=r.y-reference.y;
double hort=r.x-reference.x;
/**//* System.out.println("reference.x:"+reference.x);
System.out.println("r.x:"+r.x);
System.out.println("reference.y:"+reference.y);
System.out.println("r.y:"+r.y);
System.out.println("vert:"+vert);
System.out.println("hort:"+hort); */
if (hort<0&&(vert/hort<1&&vert/hort>-1)) //左侧
return r.getTopRight().translate( 0,off_h);
else if (vert>0&&(hort/vert<1&&hort/vert>-1))//下侧
return r.getTopLeft().translate(off_w, 0);
else if (hort>0&&(vert/hort<1&&vert/hort>-1))//右侧
return r.getTopLeft().translate(-1,off_h);
else if (vert<0&&(hort/vert<1&&hort/vert>-1))//上侧
return r.getBottomLeft().translate(off_w, 0);
else
return r.getCenter();
}
}