Tale of a .NET Component (Part IV) - ' The Legend' (
Page 3 of 3 )
Displaying the Legend
The final topic for today is displaying the legend. As we saw in an earlier article, each trace has a name and a color that are assigned by the user when the trace is created. The legend, which will be displayed in the upper right corner of the component, will display the name of each trace in the corresponding color, thus enabling viewers to identify the traces on the chart. The position of the legend, as offsets from the right Y axis and the top of the component, is given by these constants:
Recall that the component has the Traces collection containing one XYTrace for each trace. To display the legend, loop through this collection and display each one in its own color, offsetting the 2nd and subsequent legend entries by the height of the text. The DrawLegend() procedure is shown in Listing 2.
Listing 2. Drawing the chart legend.
Private Sub DrawLegend(ByVal e As Graphics)
Dim deltaY As Integer
Dim xPos As Integer, yPos As Integer
' The legend.
Dim t As XYTrace
xPos = Me.Width - MYRIGHT + LEGEND_OFFSET_X
yPos = MYTOP + LEGEND_OFFSET_Y
' The height of each legend entry.
deltaY = e.MeasureString("Dummy", f).Height
For Each t In Traces
e.DrawString(t.TraceName, f, _
New SolidBrush(t.TraceColor), _
xPos, yPos)
yPos += deltaY
Next
End Sub
Take a Look!
Figure 3 shows how all of these elements appear—the axis title, axis labels, and legend. This figure also shows some plots, and I know that we have not gotten around to that code yet. But even ignoring the plots, you can see how far we have come, having created most of the elements of out XY chart component. In fact, the plots are the last major element that needs to be added. Stay tuned!