C# 图片按钮特效:鼠标移入变浅,移出恢复原样 (ImageButtonHover类)
C# 图片按钮特效:鼠标移入变浅,移出恢复原样 (ImageButtonHover类)
ImageButtonHover.cs
C# 全选
using System;
using System.Drawing.Imaging;
namespace CSFrameworkV6.Library.CommonClass
{
/// <summary>
/// 图片按钮特效:鼠标移入变浅,移出恢复原样
/// </summary>
public class ImageButtonHover
{
// 保存原始图片(用于恢复)
private Image _originalImage;
private PictureBox _pictureBox;
private float _opacity = 0.8f;// 80% 透明度效果最佳
public ImageButtonHover(PictureBox imageButton)
{
_pictureBox = imageButton;
// 先把原始图片存起来
_originalImage = imageButton.Image;
imageButton.MouseEnter += PictureBox_MouseEnter;
imageButton.MouseLeave += PictureBox_MouseLeave;
}
/// <summary>
/// 设置透明度
/// </summary>
/// <param name="opacity"></param>
public void Handing(float opacity = 0.8f)
{
_opacity = opacity;
}
/// <summary>
/// 鼠标离开 → 恢复原图
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBox_MouseLeave(object? sender, EventArgs e)
{
_pictureBox.Image = _originalImage;
}
/// <summary>
/// 鼠标进入 → 图片变浅
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <exception cref="NotImplementedException"></exception>
private void PictureBox_MouseEnter(object? sender, EventArgs e)
{
if (_originalImage == null) return;
_pictureBox.Image = ChangeOpacity(_originalImage, _opacity);
}
/// <summary>
/// 修改图片透明度(变浅效果)
/// </summary>
/// <param name="img">原始图片</param>
/// <param name="opacity">透明度 0~1,越小越浅, 0.8效果最佳</param>
/// <returns>变浅后的图片</returns>
private Image ChangeOpacity(Image img, float opacity)
{
Bitmap bmp = new Bitmap(img.Width, img.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.Matrix33 = opacity; // 透明度
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
g.DrawImage(
img,
new Rectangle(0, 0, img.Width, img.Height),
0, 0, img.Width, img.Height,
GraphicsUnit.Pixel,
attributes
);
}
return bmp;
}
}
}使用
C# 全选
new ImageButtonHover(btnLogin).Handing();
new ImageButtonHover(btnCancel).Handing();
图片按钮原图

鼠标移动到【登录】按钮

标移动到【退出】按钮

版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网





