这是 TaW 解决方案的 VB 翻译。我添加了绘制三角形标记的代码,并注释掉了通过每个标记画一条线的代码,这样我更容易看到标记的形状。因此,您要么必须在调用此函数之前为每个系列设置 MarkerStyle,要么取消注释该行。
我的图表有一些额外的系列,可以在数据点周围绘制椭圆。我不想在图例中显示那些,所以我只显示具有命名 LegendText 的系列的图例条目。这些行在下面被注释掉,但如果你想要相同的行为,你可以取消注释。
Public Function CustomCloneLegend(chart As Chart, oLeg As Legend) As Legend
Dim newL As Legend = New Legend With {
.Position = oLeg.Position,
.Docking = oLeg.Docking,
.Alignment = oLeg.Alignment,
.Font = oLeg.Font
}
' a few numbers for the drawing to play with'
Dim iw As Integer = 16
Dim iw2 As Integer = iw / 2
Dim ih As Integer = 16
Dim ih2 As Integer = ih / 2
Dim ir As Integer = 6
Dim ir2 As Integer = ir / 2
Dim lw As Integer = 3
Dim lit As LegendItem
' point array for drawing triangles, can expand to other shapes'
Dim pts(2) As Point
' we want to access the series colors!'
chart.ApplyPaletteColors()
For Each S As Series In chart.Series
ir = S.MarkerSize
' the drawing code Is only for linechart And markerstyles circle, square, triangle'
Dim bmp As Bitmap = New Bitmap(iw, ih)
Using G As Graphics = Graphics.FromImage(bmp)
Using pen As Pen = New Pen(S.Color, lw)
Using Brush As SolidBrush = New SolidBrush(S.Color)
' Commented out the next line: Makes it hard to see the marker 'shapes
'G.DrawLine(pen, 0, ih2, iw, ih2) '
Select Case S.MarkerStyle
Case MarkerStyle.Circle
G.FillEllipse(Brush, iw2 - ir2, ih2 - ir2, ir, ir)
Case MarkerStyle.Square
G.FillRectangle(Brush, iw2 - ir2, ih2 - ir2, ir, ir)
Case MarkerStyle.Triangle
pts(0) = New Point(iw2, ih2)
pts(1) = New Point(1, ih)
pts(2) = New Point(iw - 1, ih)
G.FillPolygon(Brush, pts)
End Select
' add a New NamesImage '
Dim ni As NamedImage = New NamedImage(S.Name, bmp)
chart.Images.Add(ni)
' create And add the custom legend item '
'Uncomment the If block to hide legend labels for series with no LegendText '
'If S.LegendText <> "" Then '
lit = New LegendItem(S.Name, Color.Red, S.Name) With {
.MarkerStyle = MarkerStyle.None,
.ImageStyle = LegendImageStyle.Marker
}
newL.CustomItems.Add(lit)
'End If '
End Using
End Using
End Using
Next
oLeg.Enabled = False
Return newL
End Function