Rendering to Graphics2D with Transformations

Skip to end of metadata
Go to start of metadata
Aspose.Metafiles allows not only create default RenderedImage but also play metafile directly to the standard Graphics2D context and as a result possibility to set necessary RenderingHints . In this topic, we will show example how to render metafile without antialiasing and with custom scale factor.

Custom Metafiles Rendering

We use standard Metafile Companion Test Chart as source.


Figure : Source Metafile

In this example we will do next steps:

  • Open source wmf metafile.
  • Create BufferedImage with size equal to the 50% of the real metafile size.
  • Obtain reference to the Graphics2D object for created BufferedImage.
  • Play our metafile to the obtained Graphics2D and scale it to get half-size image.

Example:

Java
 try
 {
    // Instantiate a EmfMetafile/WmfMetafile object that represents a metafile
    WmfMetafile wmf = new WmfMetafile(new FileInputStream(new File("MFCompanion.wmf")));


    // Creating BufferedImage
    BufferedImage bimage = new BufferedImage(
          (int)(wmf.getWidth() / 2.0 + 0.5),
          (int)(wmf.getHeight() / 2.0 + 0.5),
          BufferedImage.TYPE_3BYTE_BGR);


    // Obtaining reference to the Graphics2D object
    Graphics2D graphics = bimage.createGraphics();


    // Turn on antialiasing for this Graphics2D
    Map map = new HashMap();
    map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    map.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graphics.addRenderingHints(map);


    // Fill image background with White color
    graphics.setPaint(Color.WHITE);
    graphics.fill(new Rectangle(0, 0, bimage.getWidth(), bimage.getHeight()));


    // Add scale transformation
    AffineTransform trans = AffineTransform.getScaleInstance(0.5, 0.5);
    graphics.setTransform(trans);


    // Play metafile to the Graphics2D
    wmf.playMetafile(graphics);


    // Save created image as png file
    FileOutputStream stream = new FileOutputStream("MFCompanion.png");
    PNGEncodeParam param = PNGEncodeParam.getDefaultEncodeParam(bimage);
    ImageEncoder enc = ImageCodec.createImageEncoder("PNG", stream, param);
    enc.encode(bimage);
    stream.close();
 }
 catch(Exception ex)
 {
    System.out.println(ex.toString());
 }
 

After executing this code example we should get this image:


Figure : Created PNG image

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.