我在使用WPF时遇到了一些严重问题,并且使用DrawingContext
,或者特别是VisualDrawingContext
来自覆盖元素OnRender
或使用DrawingVisual.RenderOpen()
。
问题在于分配了很多。例如,每次使用绘图上下文时,它似乎都在分配byte[]
缓冲区。
如何使用绘图上下文的示例。
using (var drawingContext = m_drawingVisual.RenderOpen())
{
// Many different drawingContext.Draw calls
// E.g. DrawEllipse, DrawRectangle etc.
}
或
override void OnRender(DrawingContext drawingContext)
{
// Many different drawingContext.Draw calls
// E.g. DrawEllipse, DrawRectangle etc.
}
这导致大量分配,导致一些不必要的垃圾收集。所以是的,我需要这个,请继续关注主题:)。
使用零或低托管堆分配数在WPF中绘制的选项有哪些?重用对象很好,但我还没有找到一种方法来做到这一点......或者它没有DependencyProperty
的问题以及它周围/内部的分配。
我确实知道WritableBitmapEx
,但希望找到一个不涉及光栅化到预定义位图的解决方案,而是适当的" vector"例如,仍然可以缩放的图形。
注意:CPU使用率是一个问题,但远低于此造成的巨大垃圾压力。
更新:我正在寻找.NET Framework 4.5+的解决方案,如果以后的版本中有任何内容,例如4.7这可能有助于解决这个问题。但它适用于桌面.NET Framework。
更新2:两个主要方案的简要说明。所有示例都已使用CLRProfiler
进行了分析,并且它清楚地表明由于此而发生了大量分配,这对我们的用例来说是一个问题。请注意,这是用于传达原则而不是确切代码的示例代码。
A :此方案如下所示。基本上,会显示一个图像,并通过自定义DrawingVisualControl
绘制一些叠加图形,然后使用using (var drawingContext = m_drawingVisual.RenderOpen())
获取绘图上下文,然后通过它绘制。绘制了大量的椭圆,矩形和文本。此示例还显示了一些缩放内容,这仅适用于缩放等。
<Viewbox x:Name="ImageViewbox" VerticalAlignment="Center" HorizontalAlignment="Center">
<Grid x:Name="ImageGrid" SnapsToDevicePixels="True" ClipToBounds="True">
<Grid.LayoutTransform>
<ScaleTransform x:Name="ImageTransform" CenterX="0" CenterY="0"
ScaleX="{Binding ElementName=ImageScaleSlider, Path=Value}"
ScaleY="{Binding ElementName=ImageScaleSlider, Path=Value}" />
</Grid.LayoutTransform>
<Image x:Name="ImageSource" RenderOptions.BitmapScalingMode="NearestNeighbor" SnapsToDevicePixels="True"
MouseMove="ImageSource_MouseMove" />
<v:DrawingVisualControl x:Name="DrawingVisualControl" Visual="{Binding DrawingVisual}"
SnapsToDevicePixels="True"
RenderOptions.BitmapScalingMode="NearestNeighbor"
IsHitTestVisible="False" />
</Grid>
</Viewbox>
`DrawingVisualControl定义为:
public class DrawingVisualControl : FrameworkElement
{
public DrawingVisual Visual
{
get { return GetValue(DrawingVisualProperty) as DrawingVisual; }
set { SetValue(DrawingVisualProperty, value); }
}
private void UpdateDrawingVisual(DrawingVisual visual)
{
var oldVisual = Visual;
if (oldVisual != null)
{
RemoveVisualChild(oldVisual);
RemoveLogicalChild(oldVisual);
}
AddVisualChild(visual);
AddLogicalChild(visual);
}
public static readonly DependencyProperty DrawingVisualProperty =
DependencyProperty.Register("Visual",
typeof(DrawingVisual),
typeof(DrawingVisualControl),
new FrameworkPropertyMetadata(OnDrawingVisualChanged));
private static void OnDrawingVisualChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dcv = d as DrawingVisualControl;
if (dcv == null) { return; }
var visual = e.NewValue as DrawingVisual;
if (visual == null) { return; }
dcv.UpdateDrawingVisual(visual);
}
protected override int VisualChildrenCount
{
get { return (Visual != null) ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
return this.Visual;
}
}
B :第二种情况涉及绘制一个移动的网格&#34;例如,数据20行100列,其中元素由边框和具有不同颜色的文本组成,以显示某些状态。网格根据外部输入移动,现在每秒仅更新5-10次。 30 fps会更好。因此,这会更新ObservableCollection
中绑定到ListBox
(VirtualizingPanel.IsVirtualizing="True"
)且ItemsPanel
为Canvas
的2000个项目。在我们的正常使用情况下,我们甚至无法显示这一点,因为它的分配太多,以至于GC停顿变得太长而频繁。
<ListBox x:Name="Items" Background="Black"
VirtualizingPanel.IsVirtualizing="True" SnapsToDevicePixels="True">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type vm:ElementViewModel}">
<Border Width="{Binding Width_mm}" Height="{Binding Height_mm}"
Background="{Binding BackgroundColor}"
BorderBrush="{Binding BorderColor}"
BorderThickness="3">
<TextBlock Foreground="{Binding DrawColor}" Padding="0" Margin="0"
Text="{Binding TextResult}" FontSize="{Binding FontSize_mm}"
TextAlignment="Center" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Canvas.Left" Value="{Binding X_mm}"/>
<Setter Property="Canvas.Top" Value="{Binding Y_mm}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True"
Width="{Binding CanvasWidth_mm}"
Height="{Binding CanvasHeight_mm}"
/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
这里有很多数据绑定,值类型的框确实需要进行大量分配,但这不是主要问题。这是WPF完成的分配。
答案 0 :(得分:1)
您的代码不可用,所以我只能建议。 在性能方面,请使用Microsoft提供的分析工具。 您可以找到工具here
您可以阅读的另一个重要链接是WPF graphics
注意: - 尝试使用绘图组
答案 1 :(得分:1)
WinForms Canvas
解决方案存在一些问题,特别是所谓的&#34;空域&#34;因WindowsFormsHost
与WPF交互的问题。为了简短起见,这意味着不能在主机上绘制WPF视觉效果。
这可以通过识别,因为我们必须双倍缓冲,我们也可以缓冲到WriteableBitmap
,然后可以通过Image
控件照常绘制。
这可以通过使用如下所示的实用程序类来实现:
using System;
using System.Drawing;
using System.Windows;
using SWM = System.Windows.Media;
using SWMI = System.Windows.Media.Imaging;
public class GdiGraphicsWriteableBitmap
{
readonly Action<Rectangle, Graphics> m_draw;
SWMI.WriteableBitmap m_wpfBitmap = null;
Bitmap m_gdiBitmap = null;
public GdiGraphicsWriteableBitmap(Action<Rectangle, Graphics> draw)
{
if (draw == null) { throw new ArgumentNullException(nameof(draw)); }
m_draw = draw;
}
public SWMI.WriteableBitmap WriteableBitmap => m_wpfBitmap;
public bool IfNewSizeResizeAndDraw(int width, int height)
{
if (m_wpfBitmap == null ||
m_wpfBitmap.PixelHeight != height ||
m_wpfBitmap.PixelWidth != width)
{
Reset();
// Can't dispose wpf
const double Dpi = 96;
m_wpfBitmap = new SWMI.WriteableBitmap(width, height, Dpi, Dpi,
SWM.PixelFormats.Bgr24, null);
var ptr = m_wpfBitmap.BackBuffer;
m_gdiBitmap = new Bitmap(width, height, m_wpfBitmap.BackBufferStride,
System.Drawing.Imaging.PixelFormat.Format24bppRgb, ptr);
Draw();
return true;
}
return false;
}
public void Draw()
{
if (m_wpfBitmap != null)
{
m_wpfBitmap.Lock();
int width = m_wpfBitmap.PixelWidth;
int height = m_wpfBitmap.PixelHeight;
{
using (var g = Graphics.FromImage(m_gdiBitmap))
{
m_draw(new Rectangle(0, 0, width, height), g);
}
}
m_wpfBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
m_wpfBitmap.Unlock();
}
}
// If window containing this is not shown, one can Reset to stop draw or similar...
public void Reset()
{
m_gdiBitmap?.Dispose();
m_wpfBitmap = null;
}
}
然后将ImageSource
绑定到XAML中的Image
:
<Grid x:Name="ImageContainer" SnapsToDevicePixels="True">
<Image x:Name="ImageSource"
RenderOptions.BitmapScalingMode="HighQuality" SnapsToDevicePixels="True">
</Image>
</Grid>
并且处理在Grid上调整大小以使WriteableBitmap的大小匹配,例如:
public partial class SomeView : UserControl
{
ISizeChangedViewModel m_viewModel = null;
public SomeView()
{
InitializeComponent();
this.DataContextChanged += OnDataContextChanged;
}
void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (m_viewModel != null)
{
this.ImageContainer.SizeChanged -= ImageSource_SizeChanged;
}
m_viewModel = e.NewValue as ISizeChangedViewModel;
if (m_viewModel != null)
{
this.ImageContainer.SizeChanged += ImageSource_SizeChanged;
}
}
private void ImageSource_SizeChanged(object sender, SizeChangedEventArgs e)
{
var newSize = e.NewSize;
var width = (int)Math.Round(newSize.Width);
var height = (int)Math.Round(newSize.Height);
m_viewModel?.SizeChanged(width, height);
}
}
这样,您可以使用WinForms / GDI +进行零堆分配绘图,如果您愿意,甚至可以使用WriteableBitmapEx
。请注意,您可以通过GDI + incl获得出色的DrawString
支持。 MeasureString
。
缺点是这是光栅化的,有时会出现一些插值问题。因此,请务必在父窗口/用户控件上设置UseLayoutRounding="True"
。
答案 2 :(得分:0)
使用WindowsFormsHost和GDI +中描述的Walkthrough: Hosting a Windows Forms Control in WPF by Using XAML进行绘图。这不是一个完美的解决方案,但是 - 现在 - 我能找到的最好的选择。
<Grid>
<WindowsFormsHost x:Name="WinFormsHost>
<custom:Canvas x:Name="Canvas" />
</WindowsFormsHost>
</Grid>
然后创建自定义控件并覆盖OnPaint
,例如:
public partial class Canvas
: UserControl
{
// Implementing custom double buffered graphics, since this is a lot
// faster both when drawing and with respect to GC, since normal
// double buffered graphics leaks disposable objects that the GC needs to finalize
protected BufferedGraphicsContext m_bufferedGraphicsContext =
new BufferedGraphicsContext();
protected BufferedGraphics m_bufferedGraphics = null;
protected Rectangle m_currentClientRectangle = new Rectangle();
public Canvas()
{
InitializeComponent();
Setup();
}
private void Setup()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint |
ControlStyles.Opaque | ControlStyles.ResizeRedraw, true);
DoubleBuffered = false;
this.Dock = DockStyle.Fill;
}
private void DisposeManagedResources()
{
m_bufferedGraphicsContext.Dispose();
if (m_bufferedGraphics != null)
{
m_bufferedGraphics.Dispose();
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Background paint is done in OnPaint
// This reduces the "leaks" of System.Windows.Forms.Internal.DeviceContext
// and the amount of "GC" handles created considerably
// as found by using CLR Profiler
}
protected override void OnPaint(PaintEventArgs e)
{
// Specifically not calling base here since we draw entire area ourselves
// base.OnPaint(e);
// Should this be disposed?
using (e)
using (var targetGraphics = e.Graphics)
{
ReallocBufferedGraphics(targetGraphics);
// Use buffered graphics object
var graphics = m_bufferedGraphics.Graphics;
// Raise paint event
PaintEvent?.Invoke(this.ClientRectangle, e.ClipRectangle, graphics);
// Render to target graphics i.e. paint event args graphics
m_bufferedGraphics.Render(targetGraphics);
}
}
protected virtual void ReallocBufferedGraphics(Graphics graphics)
{
Rectangle newClientRectangle = this.ClientRectangle;
// Realloc if new client rectangle is not contained within the current
// or if no buffered graphics exists
bool reallocBufferedGraphics = ShouldBufferBeReallocated(newClientRectangle);
if (reallocBufferedGraphics)
{
if (m_bufferedGraphics != null)
{
m_bufferedGraphics.Dispose();
}
m_bufferedGraphics = m_bufferedGraphicsContext.Allocate(
graphics, newClientRectangle);
m_currentClientRectangle = newClientRectangle;
}
}
protected virtual bool ShouldBufferBeReallocated(Rectangle newClientRectangle)
{
return !m_currentClientRectangle.Contains(newClientRectangle) ||
m_bufferedGraphics == null;
}
/// <summary>
/// PaintEvent with <c>clientRectangle, clipRectangle, graphics</c> for the canvas.
/// </summary>
public event Action<Rectangle, Rectangle, Graphics> PaintEvent;
}
更新:更新了Canvas控件以真正零堆分配。