我正在使用Viewport3D的wpf用户控件库中开发一个wpf用户控件。
我在运行应用程序的viewport中看到图像,如果我在 WPF应用程序中调用它,我可以使用RenderTargetBitmap将其保存到文件中。
但是,如果我在控制台应用程序中实例化用户控件并尝试导出,则保存空图像。代码是
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(DoIt);
t.SetApartmentState(ApartmentState.STA);
t.Start();
Console.WriteLine("press enter");
Console.ReadLine();
}
static void DoIt()
{
var x = new WpfControlLibrary1.Showcase();
x.GenerateViewPort();
x.TakeScreenshot(300, 300);
}
}
public partial class Showcase : UserControl
{
private PerspectiveCamera _PerspectiveCamera = null;
public Showcase()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler((sender, e) => this.GenerateViewPort());
}
public void GenerateViewPort()
{
this._PerspectiveCamera = new PerspectiveCamera(new Point3D(0, 0, 5), new Vector3D(0, 0, -5), new Vector3D(0, 1, 0), 45);
var viewport3D = new Viewport3D() { Camera = this._PerspectiveCamera };
viewport3D.Children.Add(new ModelVisual3D() { Content = GenerateModel() });
viewport3D.Loaded += new RoutedEventHandler(this.viewport3D_Loaded);
this.grdAniContainer.Children.Add(viewport3D);
}
private static Model3DGroup GenerateModel()
{
...
}
void viewport3D_Loaded(object sender, RoutedEventArgs e)
{
...
}
public void TakeScreenshot(int width, int height)
{
takeScreenshot(this.grdAniContainer.Children[0], width, height);
}
private static void takeScreenshot(Visual visual, int width, int height)
{
var v = visual as Viewport3D;
v.Width = width;
v.Height = height;
v.Measure(new Size(width, height));
v.Arrange(new Rect(0, 0, width, height));
var vRect = new Rectangle();
vRect.Width = width;
vRect.Height = height;
vRect.Fill = Brushes.White;
vRect.Arrange(new Rect(0, 0, vRect.Width, vRect.Height));
var bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(vRect);
bmp.Render(v);
var png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(bmp));
var dlg = new SaveFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "PNG Images (.png)|*.png";
if (dlg.ShowDialog() ?? false == true)
{
string filepath = dlg.FileName;
using (var stm = File.Create(filepath))
png.Save(stm);
}
}
}
未触发加载事件且控制台应用程序中未处理viewport3D_Loaded,因此我手动调用。
有没有办法在内存中加载视觉效果并以编程方式呈现文件?
答案 0 :(得分:0)
我需要在“takeScreenshot”方法
中实例化“bmp”后添加此委托v.Dispatcher.Invoke(((Action)(() => bmp.Render(v))), DispatcherPriority.Render);