GMF之Shapes实例Part2:设置背景图片或背景色

1、在org.eclipse.myTest.shapes.diagram工程下的icons文件夹下新建一个文件件custom,将我们用作背景的图片放进去,本例中用的是background.jpg,之后,在Eclipse中刷新org.eclipse.myTest.shapes.diagram工程。

2、在org.eclipse.myTest.shapes.diagram工程的org.eclipse.myTest.shapes.diagram.part包下新建类BackGroundLayer.java,代码如下:

package org.eclipse.myTest.shapes.diagram.part;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;

public class BackGroundLayer extends FreeformLayer {
    public static final String BACK_GROUND_LAYER = "Back ground Layer";
    private static final ImageDescriptor descriptor = ShapesDiagramEditorPlugin
            .findImageDescriptor("icons/custom/background.jpg");
    private static final Image originalImage = descriptor.createImage();
    public BackGroundLayer() {
        setOpaque(true);
    }

    @Override
    protected void paintFigure(Graphics graphics) {
        if (isOpaque()) {
            graphics.setForegroundColor(ColorConstants.white);
            graphics.setBackgroundColor(ColorConstants.white);
            graphics.fillGradient(getBounds(), true);
            graphics.setAlpha(100);// 设置透明度,背景还是颜色浅一点比较好
            graphics.drawImage(originalImage, new Point(0, 0));
        }
    }
}

3、在org.eclipse.myTest.shapes.diagram.part包下的ShapesDiagramEditor.java中的configureGraphicalViewer()的最后添加代码,如下:

//设置背景颜色
//getGraphicalViewer().getControl().setBackground(ColorConstants.orange);

//设置背景图片
DiagramRootEditPart root = (DiagramRootEditPart) getDiagramGraphicalViewer()
        .getRootEditPart();LayeredPane printableLayers = (LayeredPane) root
        .getLayer(LayerConstants.PRINTABLE_LAYERS);
BackGroundLayer backgroundLayer = new BackGroundLayer();
printableLayers.addLayerBefore(backgroundLayer,
        BackGroundLayer.BACK_GROUND_LAYER, LayerConstants.PRIMARY_LAYER);

效果图如下:

GMF之Shapes实例Part2:设置背景图片或背景色_第1张图片

但是,如果背景图片比较大,运行会比较缓慢,在接下来的例子里不使用背景图片。

程序代码请见我的代码分享http://www.oschina.net/code/snippet_164134_5913。

你可能感兴趣的:(背景,图片,GMF)