2015-09-24 76 views
-1

我剛剛開始使用GDI - 第一行是好的 - 但第二行.... 我想繪製一條簡單的對角線從(0,0) (MaxWidth,MaxHeight)。在窗體大小調整時重繪窗體時畫一條對角線

這裏是我的代碼:

Public Class Form1 
    Dim g As Graphics = Me.CreateGraphics 
    Dim stift As New Pen(Brushes.Black, 3) 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim x1 = 0, y1 = 0, x2 = Me.Size.Width, y2 = Me.Size.Height 
     g.DrawLine(stift, x1, y1, x2, y2) 
    End Sub 
End Class 

但線在第一不變形式的MaxWidth和MaxHeight結束。 有人有什麼想法嗎?

+1

擺脫CreateGraphics並使用Paint事件。此外,使用ClientSize的寬度和高度。 – LarsTech

回答

1

繪製在paint()事件的線,並允許它可以用一個按鈕來切換的快速例子:

Public Class Form1 

    Private x1 As Integer = 0 
    Private y1 As Integer = 0 
    Private x2 As Integer = 0 
    Private y2 As Integer = 0 

    Private DrawLine As Boolean = False 
    Private stift As New Pen(Brushes.Black, 3) 

    Public Sub New() 
     InitializeComponent() 

     x2 = Me.ClientSize.Width 
     y2 = Me.ClientSize.Height 
    End Sub 

    Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged 
     x2 = Me.ClientSize.Width 
     y2 = Me.ClientSize.Height 
     Me.Refresh() 
    End Sub 

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint 
     If DrawLine Then 
      Dim g As Graphics = e.Graphics 
      g.DrawLine(stift, x1, y1, x2, y2) 
     End If 
    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     DrawLine = Not DrawLine 
     Me.Refresh() 
    End Sub 

End Class 

這種方法可以讓你的COORDS從別的地方改變,並調用刷新()更新屏幕。對於多行,請考慮使用包含關於座標信息的List(),然後遍歷Paint()事件中的內容。

相關問題