Пишу класс анимаций. Начал писать код на смену прозрачности у кнопки, но столкнулся с проблемой. Хотел сделать плавность у прозрачности и поплыл в потоках. Фактический всё работает, но если я сначала наведу, потом уберу курсор, а потом снова наведу начинаются подёргивания прозрачности. Подскажите как это правильно сделать. Вот пример кода кнопки и класса:
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
eventAnimation.ChangeTransparancy(this, 150);
MouseEntered = false;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
eventAnimation.ChangeTransparancy(this, 255);
MouseEntered = false;
Invalidate();
}
Класс анимаций:
public class Animation
{
public void ChangeTransparancy(Button button, int transparancyCount)
{
Thread thread = new Thread(() => ThreadTransparancyAction(button, transparancyCount));
thread.Start();
}
public void ThreadTransparancyAction(Button button, int transparancyCount)
{
while (button.BackColor.A != transparancyCount)
{
Thread.Sleep(100);
LerpTransparancy(button, transparancyCount);
}
}
private void LerpTransparancy(Button button, int transparancy)
{
Color buttonColor = button.BackColor;
int NewTransparancyValue = (button.BackColor.A + transparancy) / 2;
if(NewTransparancyValue == transparancy - 1 && transparancy == 255)
{
button.BackColor = Color.FromArgb(255, buttonColor.R, buttonColor.G, buttonColor.B);
}
else
{
button.BackColor = Color.FromArgb(NewTransparancyValue, buttonColor.R, buttonColor.G, buttonColor.B);
}
}
}