我已经实现了两个版本的线条图代码 - 一个使用WPF形状(线条),另一个使用StreamGeometry和DrawingVisual。
DrawingVisual应该更快,但我发现完全相反。初始绘制以及随后调整包含DrawingVisual对象的主机窗口的速度非常慢且不稳定,比WPF行示例更糟糕。
我做错了什么?
WPF行代码:
Dim Rand As New Random
For i As Integer = 1 To 1000
Dim Line As New Line
Line.X1 = Rand.NextDouble * 500
Line.X2 = Rand.NextDouble * 500
Line.Y1 = Rand.NextDouble * 500
Line.Y2 = Rand.NextDouble * 500
Line.Stroke = Brushes.Black
Line.StrokeThickness = 0.25
BaseGrid.Children.Add(Line)
Next
DrawingVisual代码:
绘图视觉主机控件:
Public Class VisualHost
Inherits FrameworkElement
Dim Visual As New DrawingVisual()
Dim Context As DrawingContext
Dim Pen As Pen
Dim rand As New Random
Public Sub New()
Pen = New Pen(Brushes.Black, 0.25)
Pen.Freeze()
AddVisualChild(Visual)
End Sub
Public Sub Draw()
Dim Geometry As New StreamGeometry()
Using GeometryContext As StreamGeometryContext = Geometry.Open()
GeometryContext.BeginFigure(New Point(rand.NextDouble * 500, rand.NextDouble * 500), False, False)
For i As Integer = 1 To 1000
GeometryContext.LineTo(New Point(rand.NextDouble * 500, rand.NextDouble * 500), True, True)
Next
End Using
Geometry.Freeze()
Using Context = Visual.RenderOpen()
Context.DrawGeometry(Nothing, Pen, Geometry)
End Using
End Sub
Protected Overrides ReadOnly Property VisualChildrenCount() As Integer
Get
Return 1
End Get
End Property
Protected Overrides Function GetVisualChild(index As Integer) As Visual
Return Visual
End Function
End Class
将VisualHost分配给网格:
Private Host As New VisualHost
BaseGrid.Children.Add(Host)
Host.Draw()