2016-09-28 58 views
0

如果這是一個愚蠢的問題,請提前道歉。VB.NET圍繞中心旋轉圖形對象

我有一個圖形對象操縱一個圖像,我正在繪製一個背景的面板。我想要做的是讓圖像圍繞其中心旋轉。 下面的代碼我有到時刻:

全局聲明:

Dim myBitmap As New Bitmap("C:\Users\restofthefilepath") 
Dim g As Graphics 

Form1_Load的:

g = Panel1.CreateGraphics 

Timer1_tick(設置爲1秒的時間間隔):

Panel1.Refresh() 
g.DrawImage(myBitmap, -60, 110) 
g.RenderingOrigin = New Point(160, 68) 
g.RotateTransform(10) 

而且我得到這樣的結果:左邊是第一個打勾後,右邊是第二個打勾。 enter image description here

(佔位圖形)

正如你可以看到我設置RenderingOrigin(如this answer建議):,但轉動仍然存在0,0。我已經嘗試實現RotateTransform(10,160,68)(與指定的旋轉中心)爲this documentation說應該是可能的,但我得到一個構建錯誤「重載解析失敗,因爲沒有可訪問的'RotateTransform'接受這個數量的參數」 。

我在哪裏出錯了,如何讓圖像繞其中心旋轉?

+0

關於構建錯誤,這是因爲您正在使用Windows窗體技術,並且該文檔適用於System.Windows.Media(通常與WPF一起使用)。 –

+0

@AndrewMorton除了使用WPF重建項目之外,您還有什麼建議可以解決構建錯誤? – ForgeMonkey

+0

嗯...你是不是想改變原點,並在繪製圖像之前進行旋轉*? –

回答

1

我開始了一個新的VB.NET Windows窗體項目。我添加了一個200px x 200px的面板和一個按鈕來根據需要暫停動畫。我給Panel1的背景圖片:

enter image description here

製成的圖像有點像你這樣的:

enter image description here

,並用下面的代碼:

Public Class Form1 

    Dim wiggle As Bitmap 
    Dim tim As Timer 

    Sub MoveWiggle(sender As Object, e As EventArgs) 
     Static rot As Integer = 0 
     Panel1.Refresh() 

     Using g = Panel1.CreateGraphics() 
      Using fnt As New Font("Consolas", 12), brsh As New SolidBrush(Color.Red) 
       ' the text will not be rotated or translated 
       g.DrawString($"{rot}°", fnt, brsh, New Point(10, 10)) 
      End Using 
      ' the image will be rotated and translated 
      g.TranslateTransform(100, 100) 
      g.RotateTransform(CSng(rot)) 
      g.DrawImage(wiggle, -80, 0) 
     End Using 

     rot = (rot + 10) Mod 360 

    End Sub 

    Private Sub bnPause_Click(sender As Object, e As EventArgs) Handles bnPause.Click 
     Static isPaused As Boolean = False 
     If isPaused Then 
      tim.Start() 
      bnPause.Text = "Pause" 
     Else 
      tim.Stop() 
      bnPause.Text = "Start" 
     End If 

     isPaused = Not isPaused 

    End Sub 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     wiggle = New Bitmap("C:\temp\path3494.png") 
     wiggle.SetResolution(96, 96) ' my image had a strange resolution 
     tim = New Timer With {.Interval = 50} 
     AddHandler tim.Tick, AddressOf MoveWiggle 
     tim.Start() 

    End Sub 

    Private Sub Form1_Closing(sender As Object, e As EventArgs) Handles MyBase.Closing 
     RemoveHandler tim.Tick, AddressOf MoveWiggle 
     tim.Dispose() 
     wiggle.Dispose() 

    End Sub 

End Class 

,取得了這一點:

enter image description here

注意1:按照正確的順序設置轉換很重要。

注2:我在MyBase.Closing事件的可支配資源上調用.Dispose()。這確保內存保持乾淨並且沒有泄漏。

毫無疑問,創建動畫有更好的方式,但是在您希望的每秒一幀的情況下,這可以達到您所追求的效果。