2011-09-09 205 views
2

我想在PictureBox上繪製折線(由一個或多個線段組成的連續線)。在PictureBox上繪製折線

在此我們可以通過指定每個線段的端點以及計算每個線段的距離(即每條線的距離)來創建多條線。

Sample

+0

奈斯利問。圖像是最好的。人們喜歡誤解! – Bitterblue

回答

1

如果你想這樣做的一個圖片,最簡單的辦法是從PictureBox繼承自己的控制,並提供功能,當你按下鼠標在圖片框添加端點。

然後,您將鼠標單擊的位置存儲在列表中,並覆蓋OnPaint以繪製您的端點(一個選定的4x4方塊)和每個端點之間的一條線。這是基本的代碼:

public class EndPointPictureBox : PictureBox 
{ 
    private List<PointF> points = new List<PointF>(); 
    public EndPointPictureBox() 
    { 
    } 

    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     points.Add(new PointF(e.X,e.Y)); 
     base.OnMouseDown(e); 
     this.Invalidate(); 
    } 

    protected override void OnPaint(PaintEventArgs pe) 
    { 
     base.OnPaint(pe); 

     Graphics g = pe.Graphics; 
     foreach(var point in points) 
      g.DrawRectangle(Pens.Black,point.X-2.0f,point.Y-2.0f,4.0f,4.0f); 
     if(points.Count>1) 
      g.DrawLines(Pens.Black,points.ToArray()); 

    } 
} 

您現在可以添加這就像一個圖片形式,並選擇您imagge裏面去它以通常的方式。

如果您嘗試在圖片框內單擊幾次,您會看到它會像示例圖像一樣繪製端點。下面是我的機器的例子:

Example endpoints

然後你的下一個要求,讓端點之間的距離。這可以通過添加一個類來表示EndPoint並引用其隔壁鄰居來完成。那麼它的一些簡單的畢達哥拉斯數學來得到當前點和未來之間的距離:

public class EndPoint 
{ 
    public EndPoint(int index, List<PointF> points) 
    { 
     this.Position = points[index]; 
     if (index < points.Count - 1) 
      this.Next = points[index + 1]; 
    } 
    public PointF Position { get; private set; } 
    public PointF Next { get; private set; } 

    public double GetDistanceToNext() 
    { 
     if(this.Next == PointF.Empty) 
      return 0; 

     var xDiff = this.Position.X - Next.X; 
     var yDiff = this.Position.Y - Next.Y; 

     return Math.Abs(Math.Sqrt((xDiff*xDiff) + (yDiff*yDiff))); 
    } 
} 

,你可以添加一個方法到新的PictureBox獲得此一這些列表:

public List<EndPoint> GetEndPoints() 
{ 
    var list = new List<EndPoint>(); 
    for(var i=0;i<points.Count;i++) 
     list.Add(new EndPoint(i,points)); 
    return list; 
} 
+0

謝謝....我得到了它! – cooldj

+0

如果我想在每條線段的中間繪製計算出的距離,那我該怎麼辦?像這樣... http://i.stack.imgur.com/nPBpx.png – cooldj