Wacom Ink SDK for devices
How to save strokes drawn on the canvas as an image file
The following class can be used to render an InkDocument to a raster image:
static class InkDocumentRenderer
{
public static async Task<WriteableBitmap> RenderToBitmapAsync(InkDocument inkDocument, Color backgroundColor)
{
PixelData pixelData = Render(inkDocument, backgroundColor);
WriteableBitmap wb = new WriteableBitmap((int)pixelData.PixelWidth, (int)pixelData.PixelHeight);
using (Stream stream = wb.PixelBuffer.AsStream())
{
byte[] sourcePixels = pixelData.Data.ToArray();
await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
}
return wb;
}
public static PixelData Render(InkDocument inkDocument, Color backgroundColor)
{
const float scale = 1.0f;
Size size = new Size(inkDocument.Bounds.Width, inkDocument.Bounds.Height);
Rect rectPx;
using (Graphics graphics = new Graphics())
using (RenderingContext rc = graphics.GetRenderingContext())
using (Layer targetLayer = graphics.CreateLayer(size, scale))
{
rc.SetTarget(targetLayer);
rc.ClearColor(backgroundColor);
using (StrokeRenderer strokeRenderer = new StrokeRenderer())
{
strokeRenderer.Brush = new SolidColorBrush();
strokeRenderer.StrokeWidth = null;
strokeRenderer.UseVariableAlpha = false;
strokeRenderer.Ts = 0.0f;
strokeRenderer.Tf = 1.0f;
strokeRenderer.Init(graphics, size, scale);
RenderAllStrokesToLayer(strokeRenderer, inkDocument, targetLayer);
}
rc.SetTarget(targetLayer)
PixelData pixelData = rc.ReadPixels(out rectPx);
return pixelData;
}
}
public static void RenderAllStrokesToLayer(StrokeRenderer strokeRenderer, InkDocument inkDocument, Layer target)
{
var recursiveEnumerator = inkDocument.Root.GetEnumerator();
while (recursiveEnumerator.MoveNext())
{
if (recursiveEnumerator.Current is InkStroke s)
{
strokeRenderer.Color = s.Color;
strokeRenderer.Ts = s.Ts;
strokeRenderer.Tf = s.Tf;
// draw the stroke in the strokes layer
strokeRenderer.ResetAndClear();
strokeRenderer.DrawStroke(s.Path, 0, s.Path.PointsCount, true);
strokeRenderer.BlendStrokeInLayer(target, BlendMode.Normal);
}
}
}
}