Introduction
By placing a layer above an image and letting its alpha value increase step by step with a timer, you can realise fade effects for any image or graphics object in C#. In this example, I placed two PictureBox
es and three buttons on a form. The left-sided PictureBox
shows the original picture, while the fade effect is demonstrated inside the right-sided PictureBox
. You start everything by clicking on the "Start" button. The "Restart" button reloads the original image and lets you start the effect again. By clicking on the "Pick color" button, you can choose a different color to fade to.
Using the code
You start the effect by clicking on the "Start" button and starting the timer tFadeOut
.
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnPickColor.Enabled = false;
btnReload.Enabled = false;
tFadeOut.Start();
}
The timer ticks, and by every tick, the function Lighter()
returns the modified image for the right-sided PictureBox
until x
is incremented up to 102.
private void tFadeOut_Tick(object sender, EventArgs e)
{
if (x == 102)
{
x = 50;
tFadeOut.Stop();
btnPickColor.Enabled = true;
btnReload.Enabled = true;
}
else
pImage02.Image=Lighter(pImage02.Image, x++, colToFadeTo.R,
colToFadeTo.G, colToFadeTo.B);
}
Inside the function Lighter()
, the passed image imgLight
first gets converted into a Graphics
object. The next step is calculating the new alpha value for the mask to place above the Graphics
object. Then, this mask is created as a Pen
object with the calculated alpha value and the color to fade to. This mask gets drawn above the Graphics
object by using the method DrawLine
with the pen pLight
created in the former step. Saving the final Graphics
object by using the method graphics.Save()
also saves the new picture to the image imgLight
. The final steps are disposing the Graphics
object and returning the new, modified image.
private Image Lighter(Image imgLight, int level, int nRed, int nGreen, int nBlue)
{
Graphics graphics = Graphics.FromImage(imgLight);
int conversion = (5 * (level - 50));
Pen pLight = new Pen(Color.FromArgb(conversion, nRed,
nGreen, nBlue), imgLight.Width * 2);
graphics.DrawLine(pLight, -1, -1, imgLight.Width, imgLight.Height);
graphics.Save();
graphics.Dispose();
return imgLight;
}
History
- 27.03.2009 - First version uploaded to CodeProject.