淡出图像或图形对象






4.69/5 (9投票s)
通过修改放置在原始图像上方的新的遮罩的 alpha 值来淡出图像或图形对象。
引言
通过在图像上方放置一层,并使用计时器逐步增加其 alpha 值,可以在 C# 中实现任何图像或图形对象的淡出效果。在这个例子中,我在一个窗体上放置了两个 PictureBox
和三个按钮。左侧的 PictureBox
显示原始图像,而右侧的 PictureBox
演示了淡出效果。您可以通过单击“开始”按钮来启动所有操作。“重新开始”按钮重新加载原始图像并让您再次启动效果。通过单击“选择颜色”按钮,您可以选择不同的颜色来淡出到。
使用代码
您通过单击“开始”按钮并启动计时器 tFadeOut
来启动效果。
private void btnStart_Click(object sender, EventArgs e)
{
//disable buttons and start timer
btnStart.Enabled = false;
btnPickColor.Enabled = false;
btnReload.Enabled = false;
tFadeOut.Start();
}
计时器滴答作响,并且每次滴答,函数 Lighter()
返回修改后的图像,用于右侧的 PictureBox
,直到 x
递增到 102。
private void tFadeOut_Tick(object sender, EventArgs e)
{
if (x == 102)
{
//if x was incremented up to 102, the picture was faded
//and the buttons can be enabled again
x = 50;
tFadeOut.Stop();
btnPickColor.Enabled = true;
btnReload.Enabled = true;
}
else
//pass incremented x, and chosen color to function
//Lighter and set modified image as second picture box image
pImage02.Image=Lighter(pImage02.Image, x++, colToFadeTo.R,
colToFadeTo.G, colToFadeTo.B);
}
在函数 Lighter()
内部,传递的图像 imgLight
首先被转换为 Graphics
对象。下一步是计算要放置在 Graphics
对象上方的遮罩的新 alpha 值。然后,此遮罩作为具有计算出的 alpha 值和淡出颜色的 Pen
对象创建。此遮罩通过使用在前一步创建的笔 pLight
使用方法 DrawLine
在 Graphics
对象上方绘制。通过使用方法 graphics.Save()
保存最终的 Graphics
对象也会将新图像保存到图像 imgLight
。最后一步是释放 Graphics
对象并返回新的修改后的图像。
private Image Lighter(Image imgLight, int level, int nRed, int nGreen, int nBlue)
{
//convert image to graphics object
Graphics graphics = Graphics.FromImage(imgLight);
int conversion = (5 * (level - 50)); //calculate new alpha value
//create mask with blended alpha value and chosen color as pen
Pen pLight = new Pen(Color.FromArgb(conversion, nRed,
nGreen, nBlue), imgLight.Width * 2);
//apply created mask to graphics object
graphics.DrawLine(pLight, -1, -1, imgLight.Width, imgLight.Height);
//save created graphics object and modify image object by that
graphics.Save();
graphics.Dispose(); //dispose graphics object
return imgLight; //return modified image
}
历史
- 2009 年 3 月 27 日 - 首次版本上传至 CodeProject。