// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) 2014 OxyPlot contributors // // // Provides functionality to export plots to png. // // -------------------------------------------------------------------------------------------------------------------- #if OXYPLOT_COREDRAWING namespace OxyPlot.Core.Drawing #else namespace OxyPlot.WindowsForms #endif { 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; } /// /// 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 double Resolution { get; set; } /// /// Exports the specified model. /// /// The model. /// The file name. /// The width. /// The height. /// The resolution. public static void Export(IPlotModel model, string fileName, int width, int height, double resolution = 96) { var exporter = new PngExporter { Width = width, Height = height, Resolution = resolution }; 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 (model.Background.IsVisible()) { using (var brush = model.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, new OxyRect(0, 0, this.Width, this.Height)); } bm.SetResolution((float)this.Resolution, (float)this.Resolution); return bm; } } } }