Exporting the Canvas's Content

yFiles for Silverlight supports exporting the contents of a CanvasControl. Readily available with class CanvasControl, for example, are the following methods:

WriteableBitmap ExportToBitmap()
WriteableBitmap ExportToBitmap(RectD worldRect)
Description CanvasControl's image export methods. They enable instant image export to raw bitmap data mostly using the canvas's current settings.

Bitmap-based Image Export

Class PixelImageExporter provides support for exporting the contents of a CanvasControl to a bitmap.

Figure 6.1. PixelImageExporter

PixelImageExporter.
Raw Bitmap Export
API
RenderTargetBitmap Export(CanvasControl canvas)
Description PixelImageExporter's single export method writes raw bitmap data.

PixelImageExporter relies on a ContextConfigurator object which is given at creation time. The ContextConfigurator encapsulates information that determines the actual setup when exporting the contents of a CanvasControl. It specifies:

  • the part of the canvas that should be exported
  • the scaling factor that is applied when creating an image from the specified part of the canvas
  • what margins should be added around the exported content
  • the pixel dimensions of the resulting bitmap

Specifying the part of the canvas that should be exported is done in world coordinates, either at creation time or using the WorldBounds property. The CanvasControl's ContentRect and Viewport properties, for example, conveniently provide the world coordinates to specify the canvas's entire contents or the contents currently visible.

When using the Scale property to set the scaling factor explicitly, the pixel dimensions of an image are derived automatically. Vice versa, the scaling factor can also be derived automatically such that a desired image width or image height is achieved. The SetScaleForWidth and SetScaleForHeight methods volunteer to this end.

Example 6.16. Setting up a ContextConfigurator so that the entire content rectangle is exported

// 'myCanvas' is of type yWorks.Canvas.CanvasControl.

// The entire content as specified in the CanvasControl instance.
ContextConfigurator cc = new ContextConfigurator(myCanvas.ContentRect);
// Set the scaling factor such that we get the desired width for the exported
// content.
// Note that the margins are added to this width subsequently.
cc.SetScaleForWidth(400);

Tutorial demo application ImageExportWindow shows how PixelImageExporter can be used to export to bitmap-based file formats using a 3rd-party tool.