简体   繁体   中英

C# WPF how to draw geometry group

I'm trying to create a simple visualization with a high number of geometry objects to be drawn (10,000+), however I am currently trying to understand the proper flow of of the program. How exactly am i to draw this geometry group to the window in an efficient manner?

namespace DataVisualizer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Canvas newCanvas = new Canvas();
            DrawingGroup tmpDrawing = new DrawingGroup();
            GeometryGroup geoGroup = new GeometryGroup();
            Brush brush = new SolidColorBrush(Colors.Blue);
            int particleCount = 10000;
            int particleWidth = 5;
            int particleHeight = 5;
            Random rnd = new Random();

            //create all the geometry and add it too the geometry group
            for (int x = 0; x < particleCount; ++x)
            {
                geoGroup.Children.Add(new RectangleGeometry(new Rect(rnd.Next(500), rnd.Next(500), particleWidth, particleHeight)));
            }

            tmpDrawing.Children.Add(new GeometryDrawing(brush, null, geoGroup));


            newCanvas.Children.Add(new DrawingImage(tmpDrawing)); //does not work
            newCanvas.Background = new DrawingImage(tmpDrawing); //does not work

            //it seems i dont wana be using UIElement.. how do i effeciently draw geometry?
        }
    }
}

I find that there is not a simple explanation online outlining the general flow. Any help is greatly appreciated.

  1. [Optional] Inherit from Control to isolate the drawing logic
  2. Override OnRender(DrawingContext dc)
  3. Use DrawingContext.DrawGeometry(brush, pen, geometry)

Consider freezing brushes, pens and geometries to improve the performance. Keep in mind that DrawingContext API does not render immediately. It's more of a Builder pattern applied for drawings - it accumulates instructions of what, where and how to render.

For a particle system you may get better results by using WriteableBitmap, Viewport3D some 3rd party DirectX/OpenGL wrapper, but for 10 000 rectangles OnRender() + InvalidateVisual() may be enough

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM