我想从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();
谢谢
卢西奥
答案 0 :(得分:1)
对我来说,这个有效:
Size size = new Size(432, 460);
frameworkElement.Measure(size);
frameworkElement.Arrange(new Rect(new Point(), size));
frameworkElement.UpdateLayout();
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(frameworkElement);
FormatConvertedBitmap monoBitmap = new FormatConvertedBitmap(renderTargetBitmap, PixelFormats.BlackWhite, null, 0);
BmpBitmapEncoder bmpImage = new BmpBitmapEncoder();
bmpImage.Frames.Add(BitmapFrame.Create(monoBitmap));
byte[] bmpData;
using (MemoryStream buffer = new MemoryStream())
{
bmpImage.Save(buffer);
bmpData = buffer.ToArray();
}
很抱歉导致单色位图,这正是我使用的。这可以简单地转换为任何位图类型。