我正在尝试学习 .NET
编程。作为我学习的一部分,我尝试在按钮上制作一些效果。它正在工作......但没有我想象的那么顺利!有没有更好的方法来做到这一点?提前致谢!
我的需求:
有 3 个按钮。 当您将鼠标悬停在其中一个按钮上时,它会展开,当您将鼠标从该按钮上移开时,它会恢复到初始大小。
private void button1_MouseHover(object sender, EventArgs e)
{
button1.BackColor = Color.White;
button1.Width = 130;
button1.BringToFront();
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
button1.Width = 75;
}
private void button2_MouseHover(object sender, EventArgs e)
{
button2.BackColor = Color.Gray;
button2.Width = 130;
button2.BringToFront();
}
private void Form1_MouseLeave(object sender, EventArgs e)
{
button2.BackColor = Color.Red;
button2.Width = 75;
}
private void button3_MouseHover(object sender, EventArgs e)
{
button3.BackColor = Color.DimGray;
button3.Width = 130;
button3.BringToFront();
}
private void button3_MouseLeave(object sender, EventArgs e)
{
button3.BackColor = Color.Red;
button3.Width = 75;
}
最佳答案
所以首先,您不想做 3 次完全相同的事情。创建一个方法来为按钮添加适当的处理程序,然后只需编写代码一次即可处理任何给定的按钮。
请注意,您可以进入扩展/收缩报价处理程序并使用 percentComplete
值来设置高度,沿光谱移动颜色(虽然这将涉及一些颜色数学)或改变按钮的任何其他方面。如果您真的有动力将其概括化,您可以向 Action<double>
的方法添加一个参数。根据给定的进度百分比对对象执行某些操作。
public void AddAnimation(Button button)
{
var expandTimer = new System.Windows.Forms.Timer();
var contractTimer = new System.Windows.Forms.Timer();
expandTimer.Interval = 10;//can adjust to determine the refresh rate
contractTimer.Interval = 10;
DateTime animationStarted = DateTime.Now;
//TODO update as appropriate or make it a parameter
TimeSpan animationDuration = TimeSpan.FromMilliseconds(250);
int initialWidth = 75;
int endWidth = 130;
button.MouseHover += (_, args) =>
{
contractTimer.Stop();
expandTimer.Start();
animationStarted = DateTime.Now;
button.BackColor = Color.DimGray;
};
button.MouseLeave += (_, args) =>
{
expandTimer.Stop();
contractTimer.Start();
animationStarted = DateTime.Now;
button.BackColor = Color.Red;
};
expandTimer.Tick += (_, args) =>
{
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
if (percentComplete >= 1)
{
expandTimer.Stop();
}
else
{
button.Width = (int)(initialWidth +
(endWidth - initialWidth) * percentComplete);
}
};
contractTimer.Tick += (_, args) =>
{
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
if (percentComplete >= 1)
{
contractTimer.Stop();
}
else
{
button.Width = (int)(endWidth -
(endWidth - initialWidth) * percentComplete);
}
};
}
关于c# - 简单的按钮动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14365525/