2011-06-05 2 views
0
List<Point> pointList;   
    public int pickedIndexRight = -1; 
    public int diffX = 0; 
    public int diffY = 0; 
    public Form1() 
    { 
     InitializeComponent(); 

     pointList = new List<Point>(); 
    } 
    private void Form1_MouseDown(object sender, MouseEventArgs e) 
    { 
     Point myPoint = new Point(e.X, e.Y); 
     if (e.Button == MouseButtons.Left) 
     { 
      if (pickedIndex == -1) 
      { 
       if (pointList.Contains(myPoint) == false) 
       { 
        pointList.Add(myPoint); 
       } 
      } 
     } 
     else if (e.Button == MouseButtons.Right) 
     { 
     //if right click near a point then pickedIndexRight is index of that point in list 
     pickedIndexRight = pointList.FindIndex(delegate(Point point) { return Distance(point, myPoint) < 10; }); 
     } 
     Invalidate(); 
    } 
    private void Form1_MouseMove(object sender, MouseEventArgs e) 
    { 

     if (e.Button == MouseButtons.Right && pickedIndexRight != -1) 
     { 
      for (int i = 0; i < pointList.Count - 1; i++)//(int i = pointList.Count - 1; i > 0; i--) 
      { 
       diffX = pointList[i].X + (e.X - pointList[i].X); 
       diffY = pointList[i].Y + (e.Y - pointList[i].Y); 
       pointList[i] = new Point(diffX, diffY); 
       Invalidate(); 
      } 

     } 
    } 
    private void Form1_MouseUp(object sender, MouseEventArgs e) 
    { 
     pickedIndexRight = -1; 
     Invalidate(); 
    } 
    private double Distance(Point p1, Point p2) //calculate distance between two points 
    { 
     double d = Math.Sqrt((p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y)); 
     return d; 
    } 

    private void Form1_Paint(object sender, PaintEventArgs e) 
    { 
      foreach (Point myPoint in pointList) 
      { 
       e.Graphics.DrawRectangle(Pens.Black, myPoint.X, myPoint.Y, 1, 1); 
      } 
    } 

私は、左クリックごとにフォーム上にポイントを描画する必要があります。すべてのポイントはlistListListに格納され、次にPaintフォームで1つ1つずつ描画されます。ポイントリスト内のすべてのアイテムを変更する

私はプログラムに別の機能を持たせる必要があります - マウスの右ボタンでポイントをドラッグしてすべてのポイントを並行移動する - 私はすでにその機能を書いていますが、コードが正しく動作しません - 右クリックするとリスト全体が壊れているようです。

私はすべてのアイデアがありません。私はヒントに感謝します。この行で

+0

「i

答えて

1

diffX = pointList[i].X + (e.X - pointList[i].X); 

pointList[i].X項は相殺されます。したがって、それはちょうどです:

diffX = e.X; 

あなたは現在のマウスの位置をすべてのポイントに割り当てています。マウスが移動した距離だけすべての点を移動したいが、その位置を互いに対して保持したい場合は、マウスの以前の位置を覚えておく必要があるため、新しい位置と比較することができます。新しいマウス位置と古いマウス位置の違いは、各点に追加する正確な量です。

だから、のようなフィールドを追加します。

Point oldMousePosition; 

そして、ボタンダウンが発生したときに、それを初期化します。各移動イベントで:

pointList[i] = new Point(pointList[i].X + (e.X - oldMousePosition.X), 
         pointList[i].Y + (e.Y - oldMousePosition.Y)) 
+0

おっと、2行目にXを残してください。 –

+0

すごくうれしい –

関連する問題