从一个IFigure导出图片调用如下接口:
/**
* Returns the bytes of an encoded image for the specified
* IFigure in the specified format.
*
* @param figure the Figure to create an image for.
* @param format one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE,SWT.IMAGE_GIF
* SWT.IMAGE_ICO, SWT.IMAGE_JPEG, or SWT.IMAGE_PNG
* @return the bytes of an encoded image for the specified Figure
*/
private byte[] createImage(IFigure figure, int format) {
Device device = getEditPartViewer().getControl().getDisplay();
Rectangle r = figure.getBounds();
ByteArrayOutputStream result = new ByteArrayOutputStream();
Image image = null;
GC gc = null;
Graphics g = null;
try {
image = new Image(device, r.width, r.height);
gc = new GC(image);
g = new SWTGraphics(gc);
g.translate(r.x * -1, r.y * -1);
figure.paint(g);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] {image.getImageData()};
imageLoader.save(result, format);
} finally {
if (g != null) {
g.dispose();
}
if (gc != null) {
gc.dispose();
}
if (image != null) {
image.dispose();
}
}
return result.toByteArray();
}
传入的Figure一般对应到GraphicalViewer获得PRINTABLE_LAYERS(包括所有连线和图元),如何在不打开编辑器的情况下拿到IFigure这个对象呢?
Shell shell = new Shell();
// 创建画布
GraphicalViewer viewer = new ScrollingGraphicalViewer();
viewer.createControl(shell);
// 最底层的EditPart,会生成含多个图层的Figure
viewer.setRootEditPart(new ScalableFreeformRootEditPart());
// 传入EditPartFactory
viewer.setEditPartFactory(editPartfacoty);
// 传入容器模型,包含所有图元和连线
viewer.setContents(obj);
// 强制刷新,在内存里生成所有的图元和连线
viewer.flush();
// 获取打印层
LayerManager layers = (LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID);
IFigure figure = layers.getLayer(LayerConstants.PRINTABLE_LAYERS);
// 调用导出图片的接口
...