Search code examples
c#wpfgraphicsequivalent

equivalent CreateGraphics in wpf


So, I've used winForms .CreateGraphics to draw a variety of different things, from lines to boxes to images. It was very snappy and responsive.

I am trying to learn WPF in C#

I found that WPF allows me to "add" rectangle objects to a canvas which will display them properly. HOWEVER, I am drawing hundreds of thousands of rectangles at times, and the draw rate can become exceedingly slow, and the UI becomes less snappy when I move even 1 of the rectangles.

Painting directly onto an element in winForms was not very fast, but it was consistent regardless of how much I painted.

Is there a similar solution to doing this in WPF?

I tried adding a linq to System.Drawing, which gave me a Graphics object, but none of the wpf elements i tried have the .CreateGraphics() method.


Solution

  • You would need to create a control that overrides OnRender and do your drawing in there. There isn't a way for you to draw onto another control, but a control can draw itself.

    Also, keep in mind that WPF uses retained graphics, so if you change something you need to invalidate the visual as needed.

    EDIT:

    Something like:

    public class MyControl : Control {
    
        public MyControl() {
           this.Rects = new ObservableCollection<Rect>();
           // TODO: attach to CollectionChanged to know when to invalidate visual
        }
    
        public ObservableCollection<Rect> Rects { get; private set; }
    
        protected override void OnRender(DrawingContext dc) {
            SolidColorBrush mySolidColorBrush  = new SolidColorBrush();
            mySolidColorBrush.Color = Colors.LimeGreen;
            Pen myPen = new Pen(Brushes.Blue, 10);
    
            foreach (Rect rect in this.Rects)
                dc.DrawRectangle(mySolidColorBrush, myPen, rect);
        }
    }