我需要以矢量图形文件格式保存在 WPF UserControl 中制作的图表。
到目前为止,我尝试的是获取包含图表的 UIElement(用户控件),并将其保存为 .wmf 文件。我知道 WPF 以矢量图形格式呈现 UserControl,因此保存此文件似乎非常简单。无论如何,似乎我可以抓住用户控件,但看不到里面有什么,我试图将它放在画布中,但这似乎不起作用。我尝试使用画布,因为我已经设法从画布中的子形状保存了一个 .wmf 文件。
private void InterceptChart()
{
TChartCanvas.Children.Add(new VisualHost { Visual=chart1});
}
public class VisualHost : UIElement
{
public Visual Visual { get; set; }
protected override int VisualChildrenCount
{
get { return Visual != null ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
return Visual;
}
}
public void Export(string filePath, Canvas MyCanvas)
{
int w = Convert.ToInt32(this.MyCanvas.Width);
int h = Convert.ToInt32(this.MyCanvas.Height);
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, w, h);
Bitmap bmp = new Bitmap(16, 16);
Graphics gs = Graphics.FromImage(bmp);
Metafile mf = new Metafile(filePath, gs.GetHdc(), rect, MetafileFrameUnit.Pixel);
Graphics g = Graphics.FromImage(mf);
WPFPainter painter = new WPFPainter(g, MyCanvas);
painter.Draw(); //painter takes the child shapes from the canvas and draws them using System.Drawing.Graphics
g.Save();
g.Dispose();
mf.Dispose();
}
我真的希望有办法做到这一点,因为使用位图格式保存这些图表会使它们无用,而且我无法重新编写所有与图形相关的类,但也许我正在接近这个以错误的方式,如果是这样,如果您能指出我正确的方向,我将不胜感激。干杯!