2011-05-23 153 views
9

我借鑑了控制線在我的Windows窗體上是這樣的:如何在對象上繪製虛線?

  // Get Graphics object from chart 
      Graphics graph = e.ChartGraphics.Graphics; 

      PointF point1 = PointF.Empty; 
      PointF point2 = PointF.Empty; 

      // Set Maximum and minimum points 
      point1.X = -110; 
      point1.Y = -110; 
      point2.X = 122; 
      point2.Y = 122; 

      // Convert relative coordinates to absolute coordinates. 
      point1 = e.ChartGraphics.GetAbsolutePoint(point1); 
      point2 = e.ChartGraphics.GetAbsolutePoint(point2); 

      // Draw connection line 
      graph.DrawLine(new Pen(Color.Yellow, 3), point1, point2); 

我想知道是否有可能繪製虛線(點)行,而不是常規的實線的?

回答

22

這很簡單,一旦你figure out the formatting定義破折號:

float[] dashValues = { 5, 2, 15, 4 }; 
Pen blackPen = new Pen(Color.Black, 5); 
blackPen.DashPattern = dashValues; 
e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5)); 

float數組中的數字代表不同顏色的劃線長度。因此,對於(黑色)2個像素的簡單短劃線和每個短劃線的兩個像素:{2,2}然後重複該模式。如果你想5寬的破折號和2個像素的空間,你會使用{5,2}

在你的代碼,它看起來像:

// Get Graphics object from chart 
Graphics graph = e.ChartGraphics.Graphics; 

PointF point1 = PointF.Empty; 
PointF point2 = PointF.Empty; 

// Set Maximum and minimum points 
point1.X = -110; 
point1.Y = -110; 
point2.X = 122; 
point2.Y = 122; 

// Convert relative coordinates to absolute coordinates. 
point1 = e.ChartGraphics.GetAbsolutePoint(point1); 
point2 = e.ChartGraphics.GetAbsolutePoint(point2); 

// Draw (dashed) connection line 
float[] dashValues = { 4, 2 }; 
Pen dashPen= new Pen(Color.Yellow, 3); 
dashPen.DashPattern = dashValues; 
graph.DrawLine(dashPen, point1, point2); 
+0

感謝以至於你能告訴我,我怎麼會納入我的代碼 – 2011-05-23 17:24:54

+0

@I這:PLZ看我的編輯。但請注意。我沒有通過編譯器運行,所以可能會出現語法和意圖錯誤。無論如何,應該讓你關閉。 – 2011-05-23 17:35:15

5

筆有一個被定義爲

public DashStyle DashStyle { get; set; } 

可以設置DasStyle.Dash如果你想畫虛線的公共屬性。

5

我認爲你可以通過改變你用來繪製線條的筆來實現這一點。 所以,用替換最後2行中的例子:

 var pen = new Pen(Color.Yellow, 3); 
     pen.DashStyle = DashStyle.Dash; 
     graph.DrawLine(pen, point1, point2); 
0

在更現代的C#:

var dottedPen = new Pen(Color.Gray, width: 1) { DashPattern = new[] { 1f, 1f } };