// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) 2014 OxyPlot contributors // // // Provides functionality to export plots to png. // // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.WindowsForms { using System.Drawing; using System.Drawing.Imaging; using System.IO; /// /// Provides functionality to export plots to png. /// public class PngExporter : IExporter { /// /// Initializes a new instance of the class. /// public PngExporter() { this.Width = 700; this.Height = 400; this.Resolution = 96; this.Background = OxyColors.White; } /// /// Gets or sets the width of the output image. /// public int Width { get; set; } /// /// Gets or sets the height of the output image. /// public int Height { get; set; } /// /// Gets or sets the resolution (dpi) of the output image. /// public int Resolution { get; set; } /// /// Gets or sets the background color. /// public OxyColor Background { get; set; } /// /// Exports the specified model. /// /// The model. /// The file name. /// The width. /// The height. /// The background. public static void Export(IPlotModel model, string fileName, int width, int height, Brush background = null) { var exporter = new PngExporter { Width = width, Height = height, Background = background.ToOxyColor() }; using (var stream = File.Create(fileName)) { exporter.Export(model, stream); } } /// /// Exports the specified to the specified . /// /// The model. /// The output stream. public void Export(IPlotModel model, Stream stream) { using (var bm = this.ExportToBitmap(model)) { bm.Save(stream, ImageFormat.Png); } } /// /// Exports the specified to a . /// /// The model to export. /// A bitmap. public Bitmap ExportToBitmap(IPlotModel model) { var bm = new Bitmap(this.Width, this.Height); using (var g = Graphics.FromImage(bm)) { if (this.Background.IsVisible()) { using (var brush = this.Background.ToBrush()) { g.FillRectangle(brush, 0, 0, this.Width, this.Height); } } using (var rc = new GraphicsRenderContext(g) { RendersToScreen = false }) { model.Update(true); model.Render(rc, this.Width, this.Height); } bm.SetResolution(this.Resolution, this.Resolution); return bm; } } } }