如何在Windows Forms应用程序中使用PictureBox显示图片并添加淡入淡出特效:
Posted on 2024-06-22 17:10 lzhdim 阅读(10) 评论(0) 编辑 收藏 举报public partial class Form1 : Form { private Timer fadeTimer; private int fadeValue = 0; private bool fadeIn = true; public Form1() { InitializeComponent(); fadeTimer = new Timer(); fadeTimer.Interval = 100; // 设置定时器的时间间隔,单位为毫秒 fadeTimer.Tick += new EventHandler(OnFadeTimerTick); } private void OnFadeTimerTick(object sender, EventArgs e) { if (fadeIn) { fadeValue += 10; if (fadeValue >= 255) { fadeIn = false; fadeValue = 255; } } else { fadeValue -= 10; if (fadeValue <= 0) { fadeIn = true; fadeValue = 0; } } pictureBox1.Image = SetImageOpacity(pictureBox1.Image, fadeValue); } private Image SetImageOpacity(Image image, int opacity) { // 创建一个和原图片一样大小的Bitmap,并设置其透明度 Bitmap bmp = new Bitmap(image.Width, image.Height); using (Graphics g = Graphics.FromImage(bmp)) { ColorMatrix matrix = new ColorMatrix(); matrix.Matrix33 = opacity / 255.0f; var attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); } return bmp; } private void Form1_Load(object sender, EventArgs e) { pictureBox1.Image = Image.FromFile("path_to_your_image.jpg"); // 设置PictureBox的图片 fadeTimer.Start(); } }
Austin Liu 刘恒辉
Project Manager and Software Designer E-Mail:lzhdim@163.com Blog:https://lzhdim.cnblogs.com 欢迎收藏和转载此博客中的博文,但是请注明出处,给笔者一个与大家交流的空间。谢谢大家。 |