I want to create some kind of simulation. There will be numerous sprites floating around. Because I think that rendering every frame thousand times the same primitives which make up a sprite, will be slow, I want render them once into a bitmap and then show this sprite every frame.
But it doesn’t seem to work, the screen stays white.
My WPF source is trivial:
<Window x:Class="WPFGraphicsTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="800" Width="1000">
<Canvas>
</Canvas>
</Window>
And this is my code:
public partial class MainWindow : Window
{
Ellipse e;
RenderTargetBitmap bmp2;
public MainWindow()
{
InitializeComponent();
e = new Ellipse();
e.Width = 40;
e.Height = 40;
e.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 200));
((Canvas)this.Content).Children.Add(e);
((Canvas)this.Content).Measure(new Size(1000, 800));
((Canvas)this.Content).Arrange(new Rect(new Size(1000, 800)));
RenderTargetBitmap bmp2 = new RenderTargetBitmap(40, 40, 96, 96, PixelFormats.Pbgra32);
bmp2.Render(e);
((Canvas)this.Content).Children.Remove(e);
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
drawingContext.DrawImage(bmp2, new Rect(100,100, 40, 40));
}
}
Why doesn’t this work?
You could put an Image object on the Canvas and then use the RenderTargetBitmap to update the image. For example
Then you can update the image like this, for the example, I am just rendering a new ellipse every 100 ms. Of course you should manage the Pens and Brushes better than what I show here, this is just an example to clarify the suggestion.