New to Telerik UI for WinFormsStart a free 30-day trial

How to Draw a Moving Line Under the Mouse in RadChartView

Updated over 6 months ago

Environment

Product VersionProductAuthor
2019.2.508RadChartView for WinFormsHristo Merdjanov

Description

An example demonstrating how a line can be painted in RadChartView following the mouse position.

Solution

RadChartView already supports annotations. The solution in the article will update annotations collection upon moving the mouse.

Figure 1: Annotation Following the Mouse

chartview-moving-line 001

Implementation

C#
public partial class RadFormAnnotation : Telerik.WinControls.UI.RadForm
{
    public RadFormAnnotation()
    {
        InitializeComponent();

        FluentTheme ft = new FluentTheme();
        ThemeResolutionService.ApplicationThemeName = ft.ThemeName;

        this.radChartView1.MouseMove += RadChartView1_MouseMove;

        CandlestickSeries candlestickSeries = new CandlestickSeries();
        candlestickSeries.DataPoints.Add(new OhlcDataPoint(.00010, .00011, .00007, .00008, DateTime.Now));
        candlestickSeries.DataPoints.Add(new OhlcDataPoint(.00008, .00009, .00005, .00009, DateTime.Now.AddDays(1)));
        candlestickSeries.DataPoints.Add(new OhlcDataPoint(.00012, .00012, .00009, .00010, DateTime.Now.AddDays(2)));
        candlestickSeries.DataPoints.Add(new OhlcDataPoint(.00007, .00010, .00006, .00009, DateTime.Now.AddDays(3)));

        this.radChartView1.Series.Add(candlestickSeries);
        this.radChartView1.Axes[1].LabelFormat = "{0:N5}";
    }

    private void RadChartView1_MouseMove(object sender, MouseEventArgs e)
    {
        object hValue = this.GetVerticalAxisValueFromMouse(e);

        this.radChartView1.Annotations.Clear();
        CartesianGridLineAnnotation annotation1 = new CartesianGridLineAnnotation();
        annotation1.Value = hValue;
        annotation1.Font = new Font("Arial", 12, FontStyle.Bold);
        annotation1.Axis = this.radChartView1.Axes[1] as CartesianAxis;
        annotation1.BorderColor = Color.Red;
        annotation1.BorderDashStyle = DashStyle.Dash;
        annotation1.BorderWidth = 2;
        annotation1.Label = ((double)hValue).ToString("N5");
        this.radChartView1.Annotations.Add(annotation1);
    }

    private object GetVerticalAxisValueFromMouse(MouseEventArgs e)
    {
        LinearAxis axis = radChartView1.Axes[1] as LinearAxis;
        double delta = axis.ActualRange.Maximum - axis.ActualRange.Minimum;
        double totalHeight = axis.Model.LayoutSlot.Height;
        double ratio = 1 - (e.Location.Y - this.radChartView1.Area.View.Viewport.Y - axis.Model.LayoutSlot.Y) / totalHeight;
        double value = axis.ActualRange.Minimum + delta * ratio;

        return value;
    }
}

See Also