Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A method to draw molecules with CDK
public void drawMolecule(IMolecule molecule, String name) throws Exception {
// layout the molecule
StructureDiagramGenerator sdg = new StructureDiagramGenerator();
sdg.setMolecule(molecule, false);
// make generators
List<IGenerator<IAtomContainer>> generators = new ArrayList<IGenerator<IAtomContainer>>();
generators.add(new BasicSceneGenerator());
generators.add(new BasicBondGenerator());
generators.add(new RingPlateGenerator());
generators.add(new BasicAtomGenerator());
// setup the renderer
AtomContainerRenderer renderer = new AtomContainerRenderer(generators, new AWTFontManager());
RendererModel model = renderer.getRenderer2DModel();
model.set(BasicAtomGenerator.CompactAtom.class, true);
model.set(BasicAtomGenerator.AtomRadius.class, 6.0);
model.set(BasicAtomGenerator.CompactShape.class, BasicAtomGenerator.Shape.OVAL);
model.set(BasicAtomGenerator.KekuleStructure.class, true);
model.set(BasicBondGenerator.BondWidth.class, 5.0);
// get the image
Image image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = (Graphics2D)image.getGraphics();
g.fill(new Rectangle2D.Double(0, 0, 400, 400));
// paint
// renderer.paint(molecule, new AWTDrawVisitor(g));
renderer.paint(molecule, new AWTDrawVisitor(g),
new Rectangle2D.Double(0, 0, 400, 400), true);
// write to file
File file = new File(OUTPUT_DIR, name + ".png");
ImageIO.write((RenderedImage)image, "PNG", file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment