Terrible performance of custom-drawn control

前端 未结 3 1568
闹比i
闹比i 2020-12-01 20:23

I am making simple graph control in wpf. And I can\'t explain nor fix performance problem: it\'s too slow compared to winforms. Perhaps I am doing something wro

3条回答
  •  情深已故
    2020-12-01 20:52

    It's strange and nobody here mentioned, but it is possible to use gdi draw in wpf natively (without hosting container).

    I found this question first, which become normal render-based graph (use InvalidateVisuals() to redraw).

    protected override void OnRender(DrawingContext context)
    {
        using (var bitmap = new GDI.Bitmap((int)RenderSize.Width, (int)RenderSize.Height))
        {
            using (var graphics = GDI.Graphics.FromImage(bitmap))
            {
                // use gdi functions here, to ex.: graphics.DrawLine(...)
            }
            var hbitmap = bitmap.GetHbitmap();
            var size = bitmap.Width * bitmap.Height * 4;
            GC.AddMemoryPressure(size);
            var image = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            image.Freeze();
            context.DrawImage(image, new Rect(RenderSize));
            DeleteObject(hbitmap);
            GC.RemoveMemoryPressure(size);
        }
    }
    

    This approach is capable to draw hundred thousands of lines. Very responsive.

    Drawbacks:

    • not as smooth, as pure gdi one graph, DrawImage occurs some times after, will flickers a bit.
    • necessary to convert all wpf objects to gdi ones (sometimes is impossible): pens, brushes, points, rectangles, etc.
    • no animations, graph itself can be animated (to example, transformed), but drawings are not.

提交回复
热议问题