Tung grafik med .NET
Jeg har et problem med gentegning af et billede i VB.NET, der bruger utroligt meget CPU-kraft.For at illustrere, har jeg lavet et lille eksempel, hvor man kan åbne et billede i en Picturebox og derefter bevæge det rundt med musen - Hvorefter CPU'en straks kører på 100% i Windows jobliste.
Kan det ikke lade sig gøre at tegne et billede på en "lettere" måde?
Eksempel-kode:
Dim g, g2 As Graphics
Dim bit As Bitmap 'bruges til "offscreen" tegning
Public BgImageOffset As New PointF(0, 0)
Dim BgImage As Image
Dim LastMousePos As Point = New Point(0, 0)
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
bit = New Bitmap(PictureBox1.Width, PictureBox1.Height)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
'åbn billede
Dim Dialog As New OpenFileDialog
Dialog.Filter = "Billedfiler (*.bmp, *.gif, *.jpg)" & _
"|*.bmp;*.gif;*.jpg|Alle filer|*.*"
If Dialog.ShowDialog() = DialogResult.OK Then
BgImage = Image.FromFile(Dialog.FileName)
End If
End Sub
Private Sub UpdateDoubleBuffer()
'tegn til "offscreen" billede
g = Graphics.FromImage(bit)
g.Clear(Color.White)
If Not Me.BgImage Is Nothing Then
Dim x As Int64 = BgImageOffset.X - Me.BgImage.Width / 2
Dim y As Int64 = BgImageOffset.Y - Me.BgImage.Height / 2
Dim w As Int64 = BgImage.Width
Dim h As Int64 = BgImage.Height
g.DrawImage(BgImage, x, y, w, h)
End If
g.Dispose()
'tegn til picturebox
g2 = PictureBox1.CreateGraphics
g2.DrawImageUnscaled(bit, 0, 0)
g2.Dispose()
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
'centrer billede der hvor musen er
If e.Button = MouseButtons.Left Then
Me.BgImageOffset.X += (e.X - Me.LastMousePos.X)
Me.BgImageOffset.Y += (e.Y - Me.LastMousePos.Y)
Me.LastMousePos = New Point(e.X, e.Y)
End If
UpdateDoubleBuffer()
End Sub