// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) 2020 OxyPlot contributors
//
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.SkiaSharp
{
using global::SkiaSharp;
using System.IO;
///
/// Provides functionality to export plots to png using the SkiaSharp renderer.
///
public class PngExporter : IExporter
{
///
/// Gets or sets the DPI.
///
public float Dpi { get; set; } = 96;
///
/// Gets or sets the export height (in pixels).
///
public int Height { get; set; }
///
/// Gets or sets the export width (in pixels).
///
public int Width { get; set; }
///
/// Gets or sets a value indicating whether text shaping should be used when rendering text.
///
public bool UseTextShaping { get; set; } = true;
///
/// Exports the specified model to a file.
///
/// The model.
/// The path.
/// The width (points).
/// The height (points).
/// The DPI (dots per inch).
public static void Export(IPlotModel model, string path, int width, int height, float dpi = 96)
{
using var stream = File.OpenWrite(path);
Export(model, stream, width, height, dpi);
}
///
/// Exports the specified model to a stream.
///
/// The model.
/// The output stream.
/// The width (points).
/// The height (points).
/// The DPI (dots per inch).
public static void Export(IPlotModel model, Stream stream, int width, int height, float dpi = 96)
{
var exporter = new PngExporter { Width = width, Height = height, Dpi = dpi };
exporter.Export(model, stream);
}
///
public void Export(IPlotModel model, Stream stream)
{
using var bitmap = new SKBitmap(this.Width, this.Height);
using (var canvas = new SKCanvas(bitmap))
using (var context = new SkiaRenderContext { RenderTarget = RenderTarget.PixelGraphic, SkCanvas = canvas, UseTextShaping = this.UseTextShaping })
{
var dpiScale = this.Dpi / 96;
context.DpiScale = dpiScale;
model.Update(true);
canvas.Clear(model.Background.ToSKColor());
model.Render(context, new OxyRect(0, 0, this.Width / dpiScale, this.Height / dpiScale));
}
using var skStream = new SKManagedWStream(stream);
bitmap.Encode(skStream, SKEncodedImageFormat.Png, 0);
}
}
}