我正在使用 Viewport3D 的 wpf 用户控件库中开发 wpf 用户控件。
我在正在运行的应用程序的视口中看到图像,如果我在WPF Application中调用它,我可以使用 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);
}
}
}
Load 事件未触发,并且 viewport3D_Loaded 未在控制台应用程序中处理,因此我手动调用。
有没有办法在内存中加载视觉效果并以编程方式渲染到文件?