c# - How to dynamically export a chart in WPF? -
i working on generating dynamically chart , save image file (it not have shown in ui.) here code chart in wpf code.
<chart:piechart name="chart1" style="{staticresource minimalchartstyle}" charttitle="minimal pie chart" chartsubtitle="chart fixed width , height" selecteditem="{binding path=selecteditem, mode=twoway}" height="auto" width="auto" > <chart:piechart.series> <chart:chartseries seriestitle="errors" displaymember="category" valuemember="number" itemssource="{binding path=errors}" /> </chart:piechart.series> </chart:piechart>
.cs code like.
public observablecollection<testclass> errors { get; private set; } public mainwindow() { initializecomponent(); datacontext = this; errors = new observablecollection<testclass>(); errors.add(new testclass() { category = "globalization", number = 75 }); errors.add(new testclass() { category = "features", number = 2 }); errors.add(new testclass() { category = "contenttypes", number = 12 }); errors.add(new testclass() { category = "correctness", number = 83 }); errors.add(new testclass() { category = "best practices", number = 29 }); }
and trying method below can build chart above , save file further reference.
public bool buildchart() { clusteredbarchart newchart = new clusteredbarchart(); //newchart.actualwidth = 500; inaccessible //newchart.actualheight = 400; // t.b.d ... ... newchart.datacontext = errors; savethecharttofile(newchart); return true; } public bool savethecharttofile(chartbase view) { size size = new size(view.actualwidth, view.actualheight); if (size.isempty) return false; rendertargetbitmap result = new rendertargetbitmap((int)size.width, (int)size.height, 96, 96, pixelformats.pbgra32); drawingvisual drawingvisual = new drawingvisual(); using (drawingcontext context = drawingvisual.renderopen()) { context.drawrectangle(new visualbrush(view), null, new rect(new point(), size)); context.close(); } result.render(drawingvisual); bitmapencoder encoder = new jpegbitmapencoder(); memorystream file = new memorystream(); encoder.frames.add(bitmapframe.create(result)); encoder.save(file); system.io.file.writeallbytes("d:\\ppp.jpeg", file.toarray()); return true; }
it seems have explicitly create static chart in xaml specific width , height , on before use , export file. ?
try measure , arrange control before render it:
public bool savethecharttofile(chartbase view) { size size = new size(100, 100); rendertargetbitmap result = new rendertargetbitmap((int)size.width, (int)size.height, 96, 96, pixelformats.pbgra32); view.measure(size); view.arrange(new rect(size)); result.render(view); bitmapencoder encoder = new jpegbitmapencoder(); encoder.frames.add(bitmapframe.create(result)); using (stream stm = file.create("test.jpg")) { encoder.save(stm); } return true; }
Comments
Post a Comment