【发布时间】:2015-03-31 17:05:48
【问题描述】:
我想从 WPF 控件创建位图。我在这个论坛上看到了一些示例(最重要的是:Render a "not visible" WPF controls to an bitmap image),但只有当 WPF 控件已经显示在屏幕上时,它们才能很好地呈现。
我必须在模型中创建一个控件以将位图结果关联到他的内部位图字段。
我按照例子进入了上面的线程,但是结果是一个位图,只有控件的一部分内容(好像没有完全渲染)。
在获取图像渲染之前如何进行完整的渲染?
这是我的源代码:
if( spChart == null){
String s = "<SparrowChart xmlns=\"http://sparrowtoolkit.codeplex.com/wpf\">" +
" <SparrowChart.XAxis>" +
" <LinearXAxis/>" +
" </SparrowChart.XAxis>" +
" <SparrowChart.YAxis>" +
" <LinearYAxis/>" +
" </SparrowChart.YAxis>" +
"</SparrowChart>";
System.IO.StringReader stringReader = new System.IO.StringReader(s);
System.Xml.XmlReader xmlReader;
xmlReader = System.Xml.XmlReader.Create(stringReader);
spChart = (Sparrow.Chart.SparrowChart)System.Windows.Markup.XamlReader.Load(xmlReader);
spChart.XAxes[0].MinValue = 0;
spChart.XAxes[0].MaxValue = 10;
spChart.YAxes[0].MinValue = 0;
spChart.YAxes[0].MaxValue = 10;
spChart.Series.Clear();
} else {
spChart.Series.Clear();
}
List<System.Drawing.PointF> points = new List<System.Drawing.PointF> {new System.Drawing.PointF(3, 7),
new System.Drawing.PointF(5, 2),
new System.Drawing.PointF(8, 4),
new System.Drawing.PointF(4, 6)};
Sparrow.Chart.SeriesBase LS = new Sparrow.Chart.SplineSeries();
foreach(System.Drawing.PointF x in points) {
Sparrow.Chart.DoublePoint newPoint = new Sparrow.Chart.DoublePoint();
newPoint.Data=x.X;
newPoint.Value=x.Y;
}
spChart.Series.Add(LS);
LS = new Sparrow.Chart.ScatterSeries();
foreach(System.Drawing.PointF x in points) {
Sparrow.Chart.DoublePoint newPoint = new Sparrow.Chart.DoublePoint();
newPoint.Data=x.X;
newPoint.Value=x.Y;
}
spChart.Series.Add(LS);
spChart.Measure(new System.Windows.Size(Double.PositiveInfinity, Double.PositiveInfinity));
spChart.Arrange(new System.Windows.Rect(new System.Windows.Size(1000, 1000)));
spChart.UpdateLayout();
RenderTargetBitmap rtb = new RenderTargetBitmap((int)SpChart.ActualWidth, (int)SpChart.ActualHeight, 96, 96, Windows.Media.PixelFormats.Pbgra32);
rtb.Render(spChart);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
MemoryStream stream = New MemoryStream();
png.Save(stream);
Bitmap tmpBitmap = new Bitmap(Image.FromStream(stream));
bitmapToRender = MyBitmap.Clone();
MyBitmap.Dispose();
谢谢
卢西奥
【问题讨论】:
-
您的代码似乎没问题,除了
spChart之外还有一个SpChart变量(在RenderTargetBitmap 构造函数中)。无论如何,您可以尝试在UpdateLayout之后(或代替)添加InvalidateVisual调用。 -
对
SpChart中的情况感到抱歉。你是对的,我的源代码是spChart而不是SpChart。我认为Sparrow框架中的(InvalidateVisual和UpdateLayout都在后台工作,我必须等待他们完成布局。我找不到像RenderTerminated这样的事件,然后我放了一个计时器在10毫秒后保存位图. 现在它对我有用(它是 orrble,我现在)。
标签: wpf bitmap render sparrow-framework