几何对齐功能也是为了方便用户排列图形元素的,如果打开了此功能,当用户拖动的图形有某个边靠近另一图形的某个平行边延长线时,会自动吸附到这条延长线上;若两个图形的中心线(通过图形中心点的水平或垂直线)平行靠近时也会产生吸附效果。例如下图中,Subject1的左边与 Subject2的右边是吸附在一起的,Subject3原本是与Subject2水平中心线吸附的,而用户在拖动的过程中它的上边吸附到 Subject1的底边。
图4 几何对齐
几何对齐也是通过GraphicalViewer的属性来控制是否打开的,属性的名称是 SnapToGeometry.PROPERTY_SNAP_ENABLED,值为布尔类型。在程序里增加吸附对齐切换的功能和前面说的增加网格切换功能基本是一样的,记住GEF为它提供的Action是ToggleSnapToGeometryAction。
要实现对齐功能,还有一个重要的步骤,那就是在画布所对应的EditPart的getAdapter()方法里增加对 SnapToHelper类的回应,像下面这样:
在编辑器类中:
设置各种编辑视图的信息:
protectedvoid configureGraphicalViewer() {
super.configureGraphicalViewer();
getGraphicalViewer().setRootEditPart(new ScalableFreeformRootEditPart());
getGraphicalViewer().setProperty(
SnapToGrid.PROPERTY_GRID_VISIBLE, false);
getGraphicalViewer().setProperty(
SnapToGrid.PROPERTY_GRID_ENABLED, false);
getGraphicalViewer().setProperty(
SnapToGeometry.PROPERTY_SNAP_ENABLED, true); //getGraphicalViewer().setProperty(
SnapToGeometry.KEY_EAST_ANCHOR, true);
//getGraphicalViewer().setProperty(
SnapToGeometry.KEY_NORTH_ANCHOR, true);
//getGraphicalViewer().setProperty(
SnapToGeometry.KEY_SOUTH_ANCHOR, true);
//getGraphicalViewer().setProperty(
SnapToGeometry.KEY_WEST_ANCHOR, true);
// set the factory to use for creating EditParts
// for elements in the model
getGraphicalViewer().setEditPartFactory(new PartFactory());
getGraphicalViewer().setKeyHandler(new GraphicalViewerKeyHandler(getGraphicalViewer()).setParent(getCommonKeyHandler()));
}
/**
* 根据判断创建相关的适配器类对象
*/
@SuppressWarnings("unchecked")
@Override
public Object getAdapter(Class type){
//大纲视图
if (type == IContentOutlinePage.class)
{
returnnew OutlinePage();
//几何对齐
}elseif(type==SnapToHelper.class)
{
List snapStrategies=new ArrayList();
Boolean val=(Boolean)getGraphicalViewer().getProperty(
RulerProvider.PROPERTY_RULER_VISIBILITY);
if(val!=null&&val.booleanValue())
{
snapStrategies.add(new SnapToGuides((GraphicalEditPart)this));
}
val=(Boolean)getGraphicalViewer().getProperty(
SnapToGeometry.PROPERTY_SNAP_ENABLED);
if(val!=null&&val.booleanValue())
{
snapStrategies.add(new SnapToGeometry((GraphicalEditPart)this));
}
//网格辅助
val=(Boolean)getGraphicalViewer().getProperty(
SnapToGrid.PROPERTY_GRID_ENABLED);
if(val!=null&&val.booleanValue())
{
snapStrategies.add(new SnapToGrid((GraphicalEditPart)this));
}
if(snapStrategies.size()==0)
{
returnnull;
}
if(snapStrategies.size()==1)
{
return (SnapToHelper)snapStrategies.get(0);
}
SnapToHelper[] sth=new SnapToHelper[snapStrategies.size()];
for (int i = 0; i < snapStrategies.size(); i++) {
sth[i]=(SnapToHelper)snapStrategies.get(i);
}
returnnew CompoundSnapToHelper(sth);
}
returnsuper.getAdapter(type);
}