偷天換日讓Silverlight支持圖表轉(zhuǎn)圖片

所以實(shí)現(xiàn)圖表轉(zhuǎn)圖片可以分一下幾步走.
一.寫(xiě)一份WPF客戶端程序
思路很簡(jiǎn)單
1.1定義一個(gè)定時(shí)器,然后檢測(cè)某目錄的xml文件,這里暫定目錄名字為chart
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 2);
- timer.Tick += new EventHandler(timer_Tick);
- timer.Start();
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- }
- }
1.2如果有的話,則進(jìn)行反序列化成Chart對(duì)象進(jìn)行呈現(xiàn)
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- }
- }
- private void LoadXml(string xmlFile)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(xmlFile);
- StringReader stringReader = new StringReader(doc.InnerXml);
- XmlReader xmlReader = XmlReader.Create(stringReader);
- Chart chart = XamlReader.Load(xmlReader) as Chart;
- chart.AnimationEnabled = false;
- stringReader.Close();
- xmlReader.Close();
- this.Content=chart;
- }
1.3呈現(xiàn)好以后進(jìn)行截圖
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- PrintPicture(files[0]);
- }
- }
- private void PrintPicture(string fileName)
- {
- this.Dispatcher.BeginInvoke(new Action(() =>
- {
- int Height = (int)this.ActualHeight;
- int Width = (int)this.ActualWidth;
- RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);
- bmp.Render(this);
- string file = "C:\\temp\\a.jpg";
- BitmapEncoder encoder;
- encoder = new JpegBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bmp));
- using (Stream stm = File.Create(file))
- {
- encoder.Save(stm);
- }
- File.Delete(fileName);
- }), System.Windows.Threading.DispatcherPriority.Render);
- }
1.4轉(zhuǎn)換成圖片完畢則刪除此xml文件
二.將編譯好的wpf程序放置在web根目錄,然后啟動(dòng)此程序
三.使用ajax交互將當(dāng)前顯示出來(lái)的xml傳送到chart目錄下
前端
- $.ajax({
- type: "POST",
- url: "ajaxServer.aspx",
- data: "name=" + vChart.dataUri,
- success: function(msg) {
- alert("Success");
- }
- });
后端
拷貝xml文件或者其他處理方式把xml弄到chart目錄下
- protected void Page_Load(object sender, EventArgs e)
- {
- File.Copy(Server.MapPath(this.Request["name"]), Server.MapPath("../chart/" + this.Request["name"]));
- }
注意點(diǎn):轉(zhuǎn)換的時(shí)候注意wpf和silverlight的命名空間.也算是一個(gè)方法,對(duì)付圖表生成圖片是綽綽有余的.小技巧分享一下
【編輯推薦】



















