1、把要用到的图片放在org.eclipse.myTest.shapes.diagram工程下的icons/custom文件夹下,我用的是ReserveShapeFigure.jpg,然后刷新这个工程。
2、我想要设置图片的元素是ReserveShape1,打开ReserveShape1EditPart.java,它在该工程的org.eclipse.myTest.shapes.diagram.edit.parts包下。
3、为ReserveShape1EditPart类添加静态成员变量,代码如下:
/**
* @generated NOT
*/
private static final ImageDescriptor descriptor = ShapesDiagramEditorPlugin
.findImageDescriptor("icons/custom/ReserveShapeFigure.jpg");
private static final Image originalImage = descriptor.createImage();
public static final ImageData OrgImageData = originalImage.getImageData();
4、在ReserveShape1EditPart.java中找到类ReserveShape1Figure定义部分,也就是public class ReserveShape1Figure extends RectangleFigure {……},在类ReserveShape1Figure中覆盖paintFigure(Graphics graphics)方法:
/**
* @generated NOT
*/
public void paintFigure(Graphics graphics) {
super.paintFigure(graphics);
// 设置结点渐变颜色
// graphics.setForegroundColor(ColorConstants.blue);
// graphics.setBackgroundColor(ColorConstants.yellow);
// graphics.fillGradient(bounds, true);
// 设置结点图片,并且使得图片的大小总与图形一致
Dimension size = this.getSize();
ImageData data = OrgImageData.scaledTo(size.width, size.height);
Image image = new Image(Display.getCurrent(), data);
graphics.drawImage(image, getLocation());
}
5、运行效果如下图:
而且,可以满足图片的大小随着图形的改变而改变。
程序代码请见我的代码分享http://www.oschina.net/code/snippet_164134_5913。
来源:oschina
链接:https://my.oschina.net/u/164134/blog/30308