I am having a canvas with different objects in it, the can be moved around ..
Then i want to save the canvas to an BMP or PNG .. no problem, it works.
But if there is some object outside of the canvas, the output image will be with the desired canvas size but within the outside elements..
I want to print exactly the desired size, not more and not less .. :)
i think its an measure and arrange problem, but not figured out how it works ..
following the code and an example image of an "bad image export" !
public class Graphic_area : Canvas
{
private void SaveCanvas (string filename, bool bmp = false, int dpi = 96)
{
Size size = new Size(this.Width, this.Height);
this.Measure(size);
this.Arrange(new Rect(size));
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(this.Width * dpi / 96.0),
(int)(this.Height * dpi / 96.0),
dpi,
dpi,
PixelFormats.Default);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(this);
ctx.DrawRectangle(vb, null, new Rect(new Point(), size));
}
rtb.Render(dv);
if (bmp)
{
SaveRTBAsBMP(rtb, filename);
}
else
{
SaveRTBAsPNG(rtb, filename);
}
}
private void SaveRTBAsBMP (RenderTargetBitmap bmp, string filename)
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (var stm = System.IO.File.Create(filename))
{
encoder.Save(stm);
}
// remove alpha channel !
System.Drawing.Bitmap orig = new System.Drawing.Bitmap(filename);
System.Drawing.Bitmap clone = new System.Drawing.Bitmap(orig.Width, orig.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(clone))
{
gr.DrawImage(orig, new System.Drawing.Rectangle(0, 0, clone.Width, clone.Height));
}
orig.Dispose();
clone.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);
}
}
all on the right side of the vertical white line should not be on the picture !