我正在尝试生成一个BitmapFrame
基于UIElement
. 这是我的功能:
private BitmapFrame RenderToBitmap2()
{
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
VisualBrush aVisualBrush = new VisualBrush(GenerateTestStackPanel());
drawingContext.DrawRectangle(aVisualBrush, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150)));
drawingContext.Close();
renderBitmap.Render(drawingVisual);
return BitmapFrame.Create(renderBitmap);
}
出于测试和调试目的,我使用了一个额外的函数来创建一个简单的 StackFrame,它应该创建一个可以表示的有效视觉元素:
private StackPanel GenerateTestStackPanel()
{
// Create a red Ellipse.
Ellipse myEllipse = new Ellipse();
myEllipse.Fill = Brushes.Green;
myEllipse.StrokeThickness = 2;
myEllipse.Stroke = Brushes.Black;
// Set the width and height of the Ellipse.
myEllipse.Width = 200;
myEllipse.Height = 200;
// Add the Ellipse to the StackPanel.
StackPanel myStackPanel = new StackPanel();
myStackPanel.Children.Add(myEllipse);
return myStackPanel;
}
出于某种原因,VisualBrush 没有在 DrawRetangle(...) 函数中呈现。我可以看到绿色边框,但没有别的。此外,如果我用标准画笔换掉 VisualBrush,效果很好:
drawingContext.DrawRectangle(Brushes.Plum, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150)));
提前致谢!