0

I'm trying to create a simple sketching application.

But I've ran into a weird problem. I have a Surface Pro 3 that I'm working on, with a DPI of 144, according to some system settings.

wrong sizes

When I save the image from my app, using 96 as the dpi, it produces an image that's just a little bit smaller. Which is kind of weird.

Is there a way that I can either a) scale the canvas/strokes up that I'm saving, or tell the RenderTargetBitmap to scale properly? If I just stick 144 in there, I get the proper scale for the strokes, but my canvas size is borked.

My canvas saving code looks like this:

public void saveCanvas(object sender, RoutedEventArgs e){
    this.save_filename = this.save_filename ?? this.getSaveFilename();

    if (save_filename != null){
        var cantwo = new InkCanvas();
        cantwo.Strokes.Clear();
        cantwo.Strokes.Add(this.canvas.Strokes);
        cantwo.Background = this.canvas.Background;
        var size = new Size(this.canvas.ActualWidth, this.canvas.ActualHeight);
        cantwo.Height = size.Height;
        cantwo.Width = size.Width;
        cantwo.Measure(size);
        cantwo.Arrange(new Rect(size));
        var transform = this.canvas.LayoutTransform;
        var rtb = new RenderTargetBitmap((int)this.canvas.ActualWidth, (int)this.canvas.ActualHeight, dpiX, dpiY, PixelFormats.Default);
        rtb.Render(cantwo);
        try {
            using(var fs = File.Open(this.save_filename, FileMode.Create)){
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                encoder.Save(fs);
            }
        }
        catch(IOException){
            MessageBox.Show("Failed to save image", "ERROR: Save Failed");
        }
        // Restore transformation if there was one.
        this.canvas.LayoutTransform = transform;
    }
}

How can I save my image at the same size/resolution/dpi as my canvas? (Or draw on my canvas at the same dpi/scale as I save my image)?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • I don't really care if the canvas is smaller to match the image or if the image is bigger to match the canvas, as long as they match. – Wayne Werner Sep 30 '18 at 23:30

1 Answers1

0

Instead of creating a second InkCanvas, draw a Rectangle that is filled with a VisualBrush into a DrawingVisual:

var rect = new Rect(canvas.RenderSize);
var visual = new DrawingVisual();

using (var dc = visual.RenderOpen())
{
    dc.DrawRectangle(new VisualBrush(canvas), null, rect);
}

var rtb = new RenderTargetBitmap(
    (int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
rtb.Render(visual);
Clemens
  • 123,504
  • 12
  • 155
  • 268