eclipse中,继承ViewPart绘制ScrollingGraphicalViewer,怎么设置可以时用户在拖动ViewPart边框时ScrollingGraphicalViewer的content显示始终居中
时间: 2024-02-21 17:57:45 浏览: 102
自定一View,直接继承View,考虑padding和warp_content
要使ScrollingGraphicalViewer的content始终居中,你需要在ViewPart的createPartControl方法中设置GraphicalViewer的RootEditPart。RootEditPart是图形编辑器的根部件,你可以通过设置它的Viewport的位置来控制content的显示位置。
以下是示例代码:
```
public class YourViewPart extends ViewPart {
private ScrollingGraphicalViewer viewer;
@Override
public void createPartControl(Composite parent) {
viewer = new ScrollingGraphicalViewer();
viewer.createControl(parent);
// 设置RootEditPart
viewer.setRootEditPart(new ScalableRootEditPart() {
@Override
public void setScale(double zoom) {
super.setScale(zoom);
// 缩放时居中显示
centerViewport();
}
@Override
protected void refreshViewport() {
super.refreshViewport();
// 刷新时居中显示
centerViewport();
}
private void centerViewport() {
IFigure figure = getLayer(LayerConstants.PRIMARY_LAYER);
if (figure instanceof ScalableLayeredPane) {
ScalableLayeredPane layeredPane = (ScalableLayeredPane) figure;
Rectangle bounds = layeredPane.getBounds().getCopy();
layeredPane.translateFromParent(bounds);
layeredPane.getClientArea(Rectangle.SINGLETON);
bounds.translate(-Rectangle.SINGLETON.x, -Rectangle.SINGLETON.y);
Point viewLocation = new Point(-bounds.x, -bounds.y);
Point viewportLocation = layeredPane.getViewport().getViewLocation();
Dimension viewportSize = layeredPane.getViewport().getClientArea().getSize();
Point centerOffset = new Point((viewportSize.width - bounds.width) / 2,
(viewportSize.height - bounds.height) / 2);
Point newViewportLocation = new Point(centerOffset.x - viewLocation.x,
centerOffset.y - viewLocation.y);
if (!viewportLocation.equals(newViewportLocation)) {
layeredPane.getViewport().setViewLocation(newViewportLocation);
}
}
}
});
// 设置内容
viewer.setContents(createContents());
}
private IFigure createContents() {
// 创建RootFigure
IFigure root = new FreeformLayer();
root.setLayoutManager(new FreeformLayout());
// 创建子Figure
RectangleFigure rect = new RectangleFigure();
rect.setBackgroundColor(ColorConstants.lightGray);
rect.setBounds(new Rectangle(100, 100, 200, 100));
root.add(rect);
return root;
}
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
}
```
在上面的代码中,我们重写了ScalableRootEditPart的setScale和refreshViewport方法,在缩放和刷新时都调用了centerViewport方法,该方法会计算出content居中显示时Viewport的位置,并设置给ScalableLayeredPane的Viewport。注意,我们在创建RootEditPart时使用了FreeformLayout,这样可以自由布局子Figure。
这样,当用户拖动ViewPart边框时,GraphicalViewer的content会始终居中显示。
阅读全文