[英]Button Hover Color Change with an animation c#
我創建了一個 Windows 窗體,它有 3 個按鈕。 因此,我想通過使用 mouseenter 事件來更改顏色的一個按鈕。 這很好。 但我需要將顏色與過渡更改為淡入或淡出。 任何對此問題有答案的人請告訴我下面的代碼,我將向您展示我的 mouseenter 和 mouseleave 事件
private void button1_MouseEnter(object sender, EventArgs e)
{
button1.UseVisualStyleBackColor = false;
button1.BackColor = Color.Black;
button1.ForeColor = Color.White;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.UseVisualStyleBackColor = true;
button1.ForeColor = Color.Black;
}
這里有一些代碼可以幫助您:它通過混合 Alpha 通道引入了新的顏色。
public Form1()
{
InitializeComponent();
oldColor = button1.BackColor;
}
Color oldColor;
Color newColor = Color.FromArgb(0, Color.MediumAquamarine); // your pick, including Black
int alpha = 0;
private void button1_MouseEnter(object sender, EventArgs e)
{
alpha = 0;
timer1.Interval = 15;
timer1.Start();
}
private void button1_MouseLeave(object sender, EventArgs e)
{
timer1.Stop();
button1.BackColor = oldColor;
button1.ForeColor = Color.Black;
}
private void timer1_Tick(object sender, EventArgs e)
{
alpha += 17; // change this for greater or less speed
button1.BackColor = Color.FromArgb(alpha, newColor);
if (alpha >= 255) timer1.Stop();
if (button1.BackColor.GetBrightness() < 0.3) button1.ForeColor = Color.White;
}
編輯:如果您將 newColor 設置為太暗,則最后一條刻度線現在會將 ForeColor 設置為白色。
編輯 2 :要將相同的動畫應用於多個按鈕:
Button curButton;
MouseEnter
和MouseLeave
事件都指向上面相同的事件MouseEnter
的頂部添加這一行: Button curButton = (Button) sender;
button1
的每次出現更改為curButton
。為每個按鈕設置一個單獨的新顏色
將 newColors 存儲在 Buttons 的Tags
中,而不是類變量中:
button1.Tag = Color.MediumAquamarine;
button2.Tag = Color.MediumSeaGreen;
//..ETC.. 將此添加到MouseEnter
: newColor = (Color)curButton.Tag;
作為第二行
我開始喜歡整件事情,雖然不是黑色;-)
我為你寫了一個小例子。 它並不完美,但我認為它對你有用:)。
private void button1_MouseEnter(object sender, EventArgs e)
{
_colorCounter = 250;
button1.UseVisualStyleBackColor = false;
//button1.BackColor = Color.Black;
timer1.Start();
button1.ForeColor = Color.White;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
timer1.Stop();
_colorCounter = 250;
button1.UseVisualStyleBackColor = true;
button1.ForeColor = Color.Black;
button1.BackColor = SystemColors.Control;
}
private int _colorCounter = 250;
private void timer1_Tick(object sender, EventArgs e)
{
_colorCounter -= 25;
if (_colorCounter == 0)
{
timer1.Stop();
_colorCounter = 250;
}
else
{
// Build up a color from counter
button1.BackColor = Color.FromArgb(_colorCounter, _colorCounter, _colorCounter);
}
}
將 n 放置計時器拖放到您的表單中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.