C#- .NET上のChartコンポーネントに線を引きたい
はじめに
株価チャートとかで(部分的に)線を引きたい時にどうすればいいのか手こずったので忘れないうちに記しておく.
方法
Chart全体に線を引きたいならば
chart1.Series["candle"].ChartType = SeriesChartType.Line;
とかやって折れ線グラフを生成すればよいが,株価チャートでトレンドラインを引くときなど,気軽に2点を選択して直線を引きたい場合どうすればいいか結構時間がかかったのでまとめる.
LineAnnotationを利用した.プロパティにはX,Y,Width,Heightしかないが,WidthとHeightをうまく計算すると意図した位置に線を引くことができる.AllowSelecting,AllowMovingプロパティをtrueにすれば選択,移動もできる.他にリサイズも可能.
コード
このコードは,チャート上で2回クリックするとその2点間を結ぶ直線を生成する.LineAnnotation(線注釈)を選択してもカウントされてしまうので注意.
Point point = new Point(); private void chart1_MouseDown(object sender, MouseEventArgs e) { if (point.X == 0 && point.Y == 0) { //始点 point.X = (int)chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X); point.Y = (int)chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y); } else { //終点 Point temp = new Point(); temp.X = (int)chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X); temp.Y = (int)chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y); //線を生成 LineAnnotation ano = new LineAnnotation(); ano.AxisX = chart1.ChartAreas[0].AxisX; ano.AxisY = chart1.ChartAreas[0].AxisY; ano.IsSizeAlwaysRelative = false; ano.AllowSelecting = true; ano.AllowMoving = true; ano.X = point.X; ano.Y = point.Y; ano.Height = temp.Y - point.Y; ano.Width = temp.X - point.X; chart1.Annotations.Add(ano); point = new Point(); } }