2016-09-28 60 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()。这确保内存保持干净并且没有泄漏。

毫无疑问,创建动画有更好的方式,但是在您希望的每秒一帧的情况下,这可以达到您所追求的效果。