2015-10-03 52 views
0

我試圖重新創建一個很久以前我嘗試過的小東西。這實際上只是一個簡單的繪畫程序。該代碼基本上是:DrawLine精度?

Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown 
    X = Control.MousePosition.X 
    Y = Control.MousePosition.Y 
    Mdown = True 
End Sub 

Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove 
    Dim g As Graphics = Me.CreateGraphics 
    Dim NX As Integer = Control.MousePosition.X 
    Dim NY As Integer = Control.MousePosition.Y 
    If Mdown = True Then 
     g.DrawLine(System.Drawing.Pens.Red, X, Y, NX, NY) 
     X = NX 
     Y = NY 
    End If 

End Sub 

Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp 
    Mdown = False 
End Sub 

它工作正常,當鼠標移動時,該線從主點繪製到下一個點。但是,劃線的準確性值得懷疑。在我的第二臺顯示器(1280x720下運行)上繪製常規窗口大小(586,634)時,該線非常緊密地跟隨着鼠標尖(但不是確切的)。但是當窗口在我的主屏幕(1920x1080)上時,該線路是關閉的。這是否有一個特定的原因,因爲我認爲調用Control.MousePosition.X/Y獲得鼠標相對於窗口大小而不是屏幕大小的位置? (或別的東西)

我通常能夠自己弄清楚這些事情,但這只是一般的錯誤。有任何想法嗎?

回答

0

從MSDN:

的MousePosition屬性返回表示在財產被引用時的鼠標 光標位置點。座標表示屏幕上的位置,與控件無關,無論光標是否位於控件上,都返回 。屏幕左上角的 座標爲0,0。

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseposition%28v=vs.110%29.aspx

你得到鼠標相對於屏幕,而不是對引發事件的鼠標控制的位置。

對於後者,您應該使用MouseEventArgs變量e,特別是其Location屬性。

這樣你就可以獲得相對於你的表單而不是屏幕的位置。

E.g.

Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown 
    X = e.X 'Equal to X = e.Location.X 
    Y = e.Y 'Equal to Y = e.Location.Y 
    Mdown = True 
End Sub 

所以它不是與畫線的誤差問題,但座標提供給DrawLine方法。在你的代碼中,你可以注意到偏移量隨着你的表單在屏幕上的位置而變化。

+0

哇,我真沒想到一個快速的答覆,並添加了很多細節,您的解決方案也確實解決了問題。謝謝! – EpicMinecartz

0

當您使用CreateGraphics()進行繪製時,繪圖爲臨時(最小化/恢復應用程序並查看會發生什麼)。爲了使繪圖持續,存儲信息的GraphicsPath並通過e.Graphics塗料提供給您的圖形渲染它()事件的形式爲:

Public Class Form1 

    Private pt1 As Point 
    Private curGP As Drawing2D.GraphicsPath 
    Private GPs As New List(Of Drawing2D.GraphicsPath) 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load 
     Me.DoubleBuffered = True 
    End Sub 

    Public Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown 
     If e.Button = MouseButtons.Left Then 
      curGP = New Drawing2D.GraphicsPath 
      GPs.Add(curGP) 
      pt1 = New Point(e.X, e.Y) 
     End If 
    End Sub 

    Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove 
     If e.Button = MouseButtons.Left Then 
      Dim pt2 As New Point(e.X, e.Y) 
      curGP.AddLine(pt1, pt2) 
      pt1 = pt2 
      Me.Invalidate() 
     End If 
    End Sub 

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint 
     For Each GP As Drawing2D.GraphicsPath In GPs 
      e.Graphics.DrawPath(Pens.Red, GP) 
     Next 
    End Sub 

End Class