Skip to content

Instantly share code, notes, and snippets.

@musoftware
Created November 14, 2016 09:21
Show Gist options
  • Select an option

  • Save musoftware/d014104666b80bce569aff8e8ca06f97 to your computer and use it in GitHub Desktop.

Select an option

Save musoftware/d014104666b80bce569aff8e8ca06f97 to your computer and use it in GitHub Desktop.
Animate Color by Percentage
Imports System.Reflection
Imports System.Threading.Tasks
Public Class ColorAnimator
Public obj As New Object
Dim boolStop As New List(Of System.Threading.CancellationTokenSource)
Public Async Function Animate(ctrl As Control, prop As PropertyInfo, newColor As Color) As Threading.Tasks.Task
Dim oldColor As Color
Dim StopAni As New System.Threading.CancellationTokenSource
For Each n In boolStop
n.Cancel()
Next
boolStop.Add(StopAni)
oldColor = CType(prop.GetValue(ctrl), Color)
For index = 0 To 100 Step 5
If StopAni.IsCancellationRequested Then Exit Function
prop.SetValue(ctrl, Animate(oldColor, newColor, index))
Application.DoEvents()
Await Task.Delay(10)
Next
End Function
Private Function Animate(oldcolor As Color, newcolor As Color, precentage As Integer
) As Color
Dim r, b, g As Integer
Dim o_r As Integer = oldcolor.R, o_b As Integer = oldcolor.B, o_g As Integer = oldcolor.G
Dim n_r As Integer = newcolor.R, n_b As Integer = newcolor.B, n_g As Integer = newcolor.G
r = o_r + (n_r - o_r) * precentage / 100
g = o_g + (n_g - o_g) * precentage / 100
b = o_b + (n_b - o_b) * precentage / 100
Return Color.FromArgb(r, g, b)
End Function
End Class
Public Class Form1
Dim dColorAnimator As New ColorAnimator
Private Async Sub Panel1_MouseEnter(sender As Object, e As EventArgs) Handles Panel1.MouseEnter
Await dColorAnimator.Animate(Panel1, Panel1.GetType().GetProperty("BackColor"), Color.Red)
End Sub
Private Async Sub Panel1_MouseLeave(sender As Object, e As EventArgs) Handles Panel1.MouseLeave
Await dColorAnimator.Animate(Panel1, Panel1.GetType().GetProperty("BackColor"), Color.White)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment