標籤:
主要的功能就是使用C#畫向量圖,然後匯出到Word、Excel、Powerpoint中,並且能夠再次被編輯。以下是解決過程:
首先應該確定在Office文檔中可編輯圖形使用的格式;學習了相關資料,瞭解到Office文檔主要支援三種向量圖的格式:1、VML圖形,2、WMF檔案格式,3、EMF檔案格式。由於VML圖開一般使用HTML語言進行描述,不便於進行操作,因此決定採用WMF和EMF檔案格式。
接下來的工作就是要讓C#根據提供的資料產生WMF或EMF格式的向量圖形;學習了C#提供的GDI+繪圖類庫,GDI+可以繪製向量圖形,程式碼範例如下:
/// <summary>
/// 匯出為 Emf 或 Wmf 檔案
/// </summary>
/// <param name="filePath">檔案路徑</param>
/// <returns>是否成功</returns>
private bool Export(string filePath)
{
try
{
Bitmap bmp = new Bitmap(220,220);
Graphics gs = Graphics.FromImage(bmp);
Metafile mf = new Metafile(filePath,gs.GetHdc());
Graphics g = Graphics.FromImage(mf);
Draw(g);
g.Save();
g.Dispose();
mf.Dispose();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 繪製圖形
/// </summary>
/// <param name="g">用於繪圖的Graphics對象</param>
private void Draw(Graphics g)
{
HatchBrush hb = new HatchBrush(HatchStyle.LightUpwardDiagonal, Color.Black, Color.White);
g.FillEllipse(Brushes.Gray,10f,10f,200,200);
g.DrawEllipse(new Pen(Color.Black,1f),10f,10f,200,200);
g.FillEllipse(hb,30f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),30f,95f,30,30);
g.FillEllipse(hb,160f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),160f,95f,30,30);
g.FillEllipse(hb,95f,30f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,30f,30,30);
g.FillEllipse(hb,95f,160f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,160f,30,30);
g.FillEllipse(Brushes.Blue,60f,60f,100,100);
g.DrawEllipse(new Pen(Color.Black,1f),60f,60f,100,100);
g.FillEllipse(Brushes.BlanchedAlmond,95f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,95f,30,30);
g.DrawRectangle(new Pen(System.Drawing.Brushes.Blue,0.1f),6,6,208,208);
g.DrawLine(new Pen(Color.Black,0.1f),110f,110f,220f,25f);
g.DrawString("剖面圖",new Font("宋體",9f),Brushes.Green,220f,20f);
}
匯出Emf 或 Wmf 檔案,那就是向量圖
Metafile mf = new Metafile(filePath,gs.GetHdc());
Graphics g = Graphics.FromImage(mf);
這個代碼就是對圖形圖元檔案進行操作。
C#中如何產生向量圖