目的是将wpf组件转换为位图。如果wpf组件已经存在,则没有问题。 发生了什么事: 1.如果这是以编程方式创建的,则缺少Bitmap。 2.如果我把它放在stackpanel中,wpf中的可视化是成功的
创建位图的代码
private void Create Bitmap
{
var obj = new Button
{
Content = "BLA",
Background = Brushes.Yellow,
Foreground = Brushes.Black,
Width = 150,
Height = 40
//RenderSize = new Size(150, 40)
};
// Failure No bitmap created
BitmapSource bitmap = StaticPdf.CreateBitmapSourceFromVisual(150, 40, obj, false);
// Success, wpf show it!
_commentsTimeLine.Children.Add(obj);
}
BitmapSourceConverter的代码
public static BitmapSource CreateBitmapSourceFromVisual(Double width, Double height, Visual visualToRender,
Boolean undoTransformation)
{
if (visualToRender == null)
{
return null;
}
RenderTargetBitmap bmp = new RenderTargetBitmap((Int32) Math.Ceiling(width),
(Int32) Math.Ceiling(height), 96, 96, PixelFormats.Pbgra32);
if (undoTransformation)
{
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(visualToRender);
dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
}
bmp.Render(dv);
}
else
{
bmp.Render(visualToRender);
}
return bmp;
}
我非常感谢每一个提示
非常感谢
最好的问候