我正在尝试使用 Windows 窗体向按钮、图片框和文本框添加一些淡入淡出效果。
我知道我应该为此使用 WPF,但我从未使用过它,这对我来说太复杂了,我的项目现在要高级以切换平台。
我有这个,但不透明/褪色效果一点也不平滑。
public void Animation(Button button1) {
var expandTimer = new System.Windows.Forms.Timer();
var contractTimer = new System.Windows.Forms.Timer();
expandTimer.Interval = 10;
contractTimer.Interval = 10;
DateTime animationStarted = DateTime.Now;
TimeSpan animationDuration = TimeSpan.FromMilliseconds(250);
int initialWidth = 75;
int endWidth = 130;
button1.MouseHover += (_, args) => {
contractTimer.Stop();
expandTimer.Start();
animationStarted = DateTime.Now;
button1.ForeColor = Color.DimGray;
};
button1.MouseLeave += (_, args) => {
expandTimer.Stop();
contractTimer.Start();
animationStarted = DateTime.Now;
button1.ForeColor = Color.Red;
};
expandTimer.Tick += (_, args) => {
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
button1.Visible = false;
if (percentComplete >= 1) {
expandTimer.Stop();
} else {
button1.Width = (int)(initialWidth +
(endWidth - initialWidth) * percentComplete);
}
};
contractTimer.Tick += (_, args) => {
double percentComplete = (DateTime.Now - animationStarted).Ticks
/ (double)animationDuration.Ticks;
button1.Visible = true;
if (percentComplete >= 1) {
contractTimer.Stop();
} else {
button1.Width = (int)(endWidth -
(endWidth - initialWidth) * percentComplete);
}
};
}
如何在不切换到 WPF 的情况下修复不那么平滑的过渡?
首先我要说的是,你可能不再关心得到答案,因为这个问题已经快一年了。我觉得有必要发布这个答案,因为我认为它确实有助于回答OP的问题,不是通过提供解决方案,而是通过提供如何获得解决方案的路线图......我认为这是最好的学习方式。
让我们开始...
转换不稳定是因为当鼠标悬停在控件上时,“MouseHover”的事件处理程序会连续触发。这会导致您的动画被中断并使其显得不稳定。
我在这里的建议是,使用“MouseEnter”事件来启动计时器。
进一步研究一下,您可能会发现两个计时器之间的相似之处,并通过创建自己的计时器来使用单个计时器来完成这两项任务,该计时器具有可以由这两个事件触发的方法,以使按钮增大或缩小。
另外,尽管人们建议使用 WPF(我并不反对,WPF 很有用),但不要对 System.Windows.Forms 失去信心。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)