簡體   English   中英

如何在VB.NET中畫一條線

[英]How to draw a line in VB.NET

我想用 VB.NET 畫一條簡單的線。

我的代碼如下,但是當我運行代碼時,只顯示表單! 沒有線。

我在這里做錯了什么?

Public Class Form1
  Dim pen As System.Drawing.Graphics
  Private Sub Form1_Load(ByVal sender As System.Object,
                         ByVal e As System.EventArgs) Handles MyBase.Load
    pen = Me.CreateGraphics()
    pen.DrawLine(Pens.Azure, 10, 10, 20, 20)
  End Sub       
End Class

基本上,您做錯的是使用CreateGraphics方法。

這是您很少(如果有的話)需要做的事情。 當然,這並不是說方法被破壞了。 它完全按照它所說的做:它被記錄為這樣做:返回一個表示表單繪圖表面的Graphics對象。

問題是,每當您的表單被重繪(這可能有很多原因), Graphics對象基本上會被重置 結果,你畫進你得到的所有東西都被抹掉了。

表單總是重繪,當它第一次加載,所以使用CreateGraphics永遠是有道理的Load事件處理方法。 它也將在任何時候被最小化和恢復,被另一個窗口覆蓋,甚至調整大小(其中一些取決於您的操作系統、圖形驅動程序和表單的屬性,但這超出了重點)被重繪。

您可能會使用CreateGraphics的唯一時間是當您希望向用戶顯示不應在重繪期間持續存在的即時反饋時。 例如,在MouseMove事件的處理程序中,當顯示拖放反饋時。

那么,解決方案是什么? 始終在Paint事件處理程序方法內進行Paint 這樣,它會在重繪中持續存在,因為“重繪”基本上涉及引發Paint事件。

當引發Paint事件時,處理程序會傳遞一個PaintEventArgs類的實例,該類包含一個可以繪制的Graphics對象。

所以你的代碼應該是這樣的:

Public Class Form1

    Protected Overridable Sub OnPaint(e As PaintEventArgs)
        ' Call the base class
        MyBase.OnPaint(e)

        ' Do your painting
        e.Graphics.DrawLine(Pens.Azure, 10, 10, 20, 20)
    End Sub

End Class

(還要注意,在上面的代碼中,我覆蓋了OnPaint方法,而不是處理相應的Paint事件。這被認為是處理派生類中事件的最佳實踐。但無論哪種方式都可以。)

你應該這樣做來畫你的線

Public Class Form1
    Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
    Dim myPen As Pen

   'instantiate a new pen object using the color structure
    myPen = New Pen(Color=Color.Blue, Width=2)

   'draw the line on the form using the pen object
   e.Graphics.DrawLine(pen=myPen, x1=100, y1=150, x2=150, y2=100)

   End Sub       
End Class

或者有更簡單的解決方案,只需在 Form Paint Event 中添加此代碼

e.Graphics.DrawLine(Pens.Azure, 10, 10, 20, 20)

您應該將此代碼放在表單的Paint事件中,這里發生的是正在繪制線條,但表單在完成加載時正在重新繪制,因此您的線條消失了。 此外,嘗試使用黑色或對比色更強的顏色,否則您會在窗體的窗口背景色中錯過它。

您可以通過向表單添加一個 groupbox 控件來實現這一點。 然后刪除文本(保留空白文本),將高度設置為 1 並選擇所需的背景顏色。

繪制多條線 Dim blackPen As New Pen(Color.Red, 3) Dim hwnd As IntPtr = PictureBox1.Handle Dim myGraphics As Graphics myGraphics = Graphics.FromHwnd(hwnd) Dim x1 As Integer = 100 Dim x2 As Integer = 500 Dim y1 As Integer = 10 Dim y2 As Integer = y1 Dim i As Int16 = 10, bothgap As Int16 = 20 ' myGraphics.DrawLine(blackPen, x1, y1, x2, y2) For i = 1 to 10 myGraphics.DrawLine(blackPen, x1, y1 + i * bothgap, x2, y1 + i * bothgap) 'myGraphics.DrawLine(blackPen, x1, y1 + 2 * 20, x2, y1 + 2 * 20) 'myGraphics.DrawLine(blackPen, x1, y1 + 3 * 20, x2, y1 + 3 * 20) 接下來 x1 = 100 x2 = 100 y1 = 10 + bothgap y2 = 200 + bothgap / 2 blackPen = New Pen(Color.Blue, 3) For i = 1 To 21 ' myGraphics.DrawLine (blackPen, x1, y1, x2, y2) myGraphics.DrawLine(blackPen, x1 + (i - 1) * bothgap, y1, x2 + (i - 1) * bothgap, y2) ' myGraphics.DrawLine(blackPen, x1 + 2 * bothgap, y1, x2 + 2 * bothgap, y2) 下一個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM