如何在Chart中选取部分?
Hi lilin,
根据您的要求,建议您使用矩形来选择捕获的点,具体如何实现请参考以下代码:
Private mdown As Point = Point.Empty
Private selectedPoints As List(Of DataPoint) = Nothing
Private Sub chart1_MouseDown(sender As Object, e As MouseEventArgs)
mdown = e.Location
selectedPoints = New List(Of DataPoint)()
End Sub
Private Sub chart1_MouseMove(sender As Object, e As MouseEventArgs)
If e.Button = System.Windows.Forms.MouseButtons.Left Then
Chart1.Refresh()
Using g As Graphics = Chart1.CreateGraphics()
g.DrawRectangle(Pens.Red, GetRectangle(mdown, e.Location))
End Using
End If
End Sub
Private Sub chart1_MouseUp(sender As Object, e As MouseEventArgs)
Dim ax As Axis = Chart1.ChartAreas(0).AxisX
Dim ay As Axis = Chart1.ChartAreas(0).AxisY
Dim rect As Rectangle = GetRectangle(mdown, e.Location)
For Each dp As DataPoint In Chart1.Series(0).Points
Dim x As Integer = CInt(ax.ValueToPixelPosition(dp.XValue))
Dim y As Integer = CInt(ay.ValueToPixelPosition(dp.YValues(0)))
If rect.Contains(New Point(x, y)) Then
selectedPoints.Add(dp)
End If
Next
' optionally color the found datapoints:
For Each dp As DataPoint In Chart1.Series(0).Points
dp.Color = If(selectedPoints.Contains(dp), Color.Red, Color.Black)
Next
End Sub
Public Shared Function GetRectangle(p1 As Point, p2 As Point) As Rectangle
Return New Rectangle(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y), Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y))
End Function |