今天在写代码的时候,要实现图片的渐隐渐出效果,然后写了一下
public int opacity = 255;
private Timer fadeTimer;
private Image originalImage;
private Image currentImage;
public bool EffectMethod = true; //控制当前效果
public Form1()
{
InitializeComponent();
fadeTimer = new Timer();
fadeTimer.Interval = 50;
fadeTimer.Tick += FadeTimer_Tick;
}
private void FadeTimer_Tick(object sender, EventArgs e)
{
if (opacity < 0 || opacity > 255)
{
fadeTimer.Stop();
}
else
{
if (EffectMethod==true)
{
opacity -= 7; // 调整透明度的变化速度
}
else if(EffectMethod==false)
{
opacity += 7; // 调整透明度的变化速度
}
// 根据当前透明度创建新的图片,并调整透明度
currentImage = new Bitmap(originalImage.Width, originalImage.Height);
using (Graphics graphics = Graphics.FromImage(currentImage))
{
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.Matrix33 = opacity / 255f;
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.SetColorMatrix(colorMatrix);
graphics.DrawImage(originalImage, new Rectangle(0, 0, currentImage.Width, currentImage.Height),
0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, imageAttributes);
}
// 更新 pictureBox 的图片
pictureBox.Image = currentImage;
pictureBox.Refresh();
}
}
新建一个图片,加到panel
//渐隐效果
pictureBox = new PictureBox();
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
panel.Controls.Add(pictureBox);
string imageName = "logo";
pictureBox.Image = (Image)Properties.Resources.ResourceManager.GetObject(imageName);
pictureBox.Size = new Size(200, 200);
opacity = 255;
originalImage = pictureBox.Image;
currentImage = new Bitmap(originalImage.Width, originalImage.Height);
using (var graphics = Graphics.FromImage(currentImage))
{
graphics.DrawImage(originalImage, new Rectangle(0, 0, currentImage.Width, currentImage.Height));
}
fadeTimer.Start();
渐出效果
Task.Delay(4000).ContinueWith(_ =>
{
this.Invoke(new Action(() =>
{
Log("-----------------------------------------------");
Log("time 6 delay Start.");
Log("current opacity:"+opacity);
int a = 1;
setOpacity(a);
pictureBox.Image = (Image)Properties.Resources.ResourceManager.GetObject("warn");
originalImage = pictureBox.Image;
pictureBox.Dock = DockStyle.Fill;
currentImage = new Bitmap(originalImage.Width, originalImage.Height);
using (var graphics = Graphics.FromImage(currentImage))
{
graphics.DrawImage(originalImage, new Rectangle(0, 0, currentImage.Width, currentImage.Height));
}
EffectMethod = false;
Log("current set-opacity:" + opacity);
fadeTimer.Start();
}));
});
___END