我的画布中有不同的物体,可以四处移动..
然后我想将画布保存到BMP或PNG ..没问题,它有效。
但是如果画布外面有一些对象,输出图像将具有所需的画布大小,但在外部元素中。
我想要精确打印所需的尺寸,而不是更多而不是更少.. :)
我认为这是衡量和安排问题,但没有弄清楚它是如何运作的。
关注代码和“坏图像导出”的示例图像!
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);
}
}
垂直白线右侧的所有内容都不应出现在图片上!