2015-05-14 33 views
-1

我現在添加了起點終點和鼠標x和鼠標y變量,我想用它們在圖表控件上用左鍵單擊鼠標時畫點。如何使用鼠標點擊事件和Windows窗體圖表控件的繪圖事件來繪製圖表上的點?

但我想只繪製點的圖表區域,也只有當鼠標位於圖表的正方形區域內,因此它不會在正方形邊界線上或圖表控制區域外繪製點。

還可以在圖表中的正方形中移動鼠標以顯示標籤上的軸X和軸Y值時顯示。

左軸1至120現在的時間軸和底軸1至30天。 因此,如果我在第一個方塊區域移動鼠標,它應該會顯示第1天時間112或第2天時間33.

這就是爲什麼我也不確定X軸和Y軸的空間是否正確。 它應該是1到120和1到30,但我認爲每個方塊應該在3天內和120個時間內出現,但是在1步的1個跳躍中,所以當我用鼠標移動時,我可以在第一個方塊中看到第1天時間3或第3天時間66 方塊的下一行將呈現天4〜6

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Windows.Forms.DataVisualization.Charting; 

namespace Test 
{ 
    public partial class Form1 : Form 
    { 
     private Point startPoint = new Point(); 
     private Point endPoint = new Point(); 
     private int mouseX = 0; 
     private int mouseY = 0; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void chart1_MouseDown(object sender, MouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       mouseX = System.Windows.Forms.Cursor.Position.X; 
       mouseY = System.Windows.Forms.Cursor.Position.Y; 
       chart1.Invalidate(); 

      } 
     } 

     private void chart1_Paint(object sender, PaintEventArgs e) 
     { 
      Graphics g1 = this.CreateGraphics(); 
      Pen linePen = new Pen(Color.Green, 1); 
      Pen ellipsePen = new Pen(Color.Red, 1); 
      startPoint = new Point(mouseX, mouseY); 
      endPoint = new Point(mouseX, mouseY); 
      g1.DrawLine(linePen, startPoint, endPoint); 
      g1.DrawEllipse(ellipsePen, mouseX - 2, mouseY - 2, 4, 4); 
      linePen.Dispose(); 
      ellipsePen.Dispose(); 
      g1.Dispose(); 
     } 
    } 
} 

方式的代碼現在,它的繪圖的點是遠圖表控制區。

+1

[如何用鼠標在圖表控件中繪製圖形]的可能重複(http://stackoverflow.com/questions/29902288/how-to-draw-a-graph-in-chart-control-with-mouse ) – TaW

+0

我試過你的解決方案,它確實工作。我把你的第二個解決方案代碼,我改變了一些。相反,使用點列表我只使用paint事件中的lastPoint變量,我做了:e.Graphics.DrawEllipse(pen,lastPoint.X,lastPoint.Y,4,4);我做了它,因爲我想繪製每一次只有一個單一的點。現在的問題是,每次單擊鼠標時都會刪除最後繪製的點。我怎樣才能使它不會刪除lastPoint? –

+0

該帖子不斷將繪製的點添加到數據點集合。如果你不想要,只畫出一個點,你仍然會將它添加到系列點,或者可能是一個額外的系列;那麼你可以計算它的正確位置並用這些座標設置newPoint。最後,你會刪除數據點。我明白了嗎? – TaW

回答

1

這是因爲您使用了錯誤的鼠標座標。 替換這些行

mouseX = System.Windows.Forms.Cursor.Position.X; 
mouseY = System.Windows.Forms.Cursor.Position.Y; 

利用該:

mouseX = e.X; 
mouseY = e.Y; 

System.Windows.Forms.Cursor.Position返回使用的形式作爲鹼的鼠標的座標,而使用所提出的控制的MouseEventArgs返回鼠標的座標該事件作爲一個基地。

相關問題