Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / C#

Slide Show with Fade In/Out Effect

Rate me:
Please Sign up or sign in to vote.
3.28/5 (11 votes)
5 Oct 2007CPOL1 min read 101.5K   9.5K   43   20
Slide show with fade in and fade out effect using GDI+

Introduction

I wanted to create an application for slide show on a image viewer, but most articles that I found just click and display the next photo without any effect. With effect, most were using ASP.NET/Web Project and JavaScript. This is the reason why I write and why you read this article. Thanks to Adiphe for the Fullscreen article, please click here to read the article.

Background

I've tried to use Threading and GDI+ to make the image transparent, but unluckily the result flickers or when it is smooth, it takes a long time. Now I found a trick and I am willing to share it. After reading this article, you will know how to do fade in and out without flicker.

This time I didn't create any thread, I just called BackgroundWorker to handle the change image part and a Timer to do the effect.

Using the Code

Define the variables:

C#
private const int PAUSE_TIME = 5 * 1000; 	//Time to display image

private List<string> m_ImageFilePaths = new List<string>(); 	//List of Image Path
private MemoryStream m_ImageStream = null; 	//Current Loaded Image Stream
private Image m_CurrentImage = null; 	//Current Loaded Image
private int m_Alpha = 255; 			//Alpha level of the top layer of the image
private Fade m_CurrentAction = Fade.In; 	//Current Action
//Communicate between BackgroundWorker and Timer
private AutoResetEvent m_FinishEvent = new AutoResetEvent(false); 
//Define the display area, do not suggest calculate any formula in OnPaint 
private Rectangle m_DisplayRectangle = new Rectangle(); 
private bool m_Cancel = false; 		//Flag to check Is the SlideShow cancelled

In the constructor:

C#
public FormMain()
{
    InitializeComponent();

    //Set style to optimize the drawing effect
    this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    this.SetStyle(ControlStyles.UserPaint, true);
    this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}

Draw the image to the main windows, and draw a layer to effect the fade in and out:

C#
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    if (m_CurrentImage != null)
    {
        e.Graphics.DrawImage(m_CurrentImage, m_DisplayRectangle, 
	0, 0, m_CurrentImage.Width, m_CurrentImage.Height, GraphicsUnit.Pixel);
        //Draw the layer to effect fade in and out, 
        //the layer is same as window background color
        e.Graphics.FillRectangle(new SolidBrush
	(Color.FromArgb(m_Alpha, this.BackColor)), this.ClientRectangle);
    }
}

Change the image under BackgroundWorker:

C#
private void backgroundWorkerSlideShow_DoWork(object sender, DoWorkEventArgs e)
{
    List<string> files = (List<string>)e.Argument;
    foreach (string file in files)
    {
        if (m_Cancel)
        {
            //When user cancels the slide show, quit the loop for load image
            break;
        }

        m_CurrentAction = Fade.Out;
        UpdateTimerEnable(true);
        //Wait for Timer to finish fade out effect
        m_FinishEvent.WaitOne();

        //Clean up the image stream
        if (m_ImageStream != null)
        {
            m_ImageStream.Dispose();
            m_ImageStream = null;
        }

        using (FileStream fs = File.Open(file, FileMode.Open))
        {
            byte[] ba = new byte[fs.Length];
            fs.Read(ba, 0, ba.Length);
            m_ImageStream = new MemoryStream(ba);
            //Clean up the current image
            if (m_CurrentImage != null)
            {
                m_CurrentImage.Dispose();
                m_CurrentImage = null;
            }
            m_CurrentImage = Image.FromStream(m_ImageStream);
            int x = (this.ClientSize.Width - m_CurrentImage.Width) / 2;
            int y = (this.ClientSize.Height - m_CurrentImage.Height) / 2;
            m_DisplayRectangle = new Rectangle
		(x, y, m_CurrentImage.Width, m_CurrentImage.Height);
        }

        m_CurrentAction = Fade.In;
        UpdateTimerEnable(true);
        //Wait for Timer to finish fade in effect
        m_FinishEvent.WaitOne();

        //Sleep for display the image
        Thread.Sleep(PAUSE_TIME);
    }
}

Increase or decrease the alpha level in the Timer:

C#
private void timerFade_Tick(object sender, EventArgs e)
{
    if ((m_CurrentAction == Fade.In) && (m_Alpha > 0))
    {
        m_Alpha -= 5;
    }
    else if ((m_CurrentAction == Fade.Out) && (m_Alpha < 255))
    {
        m_Alpha += 5;
    }
    if ((m_Alpha <= 0) || (m_Alpha >= 255))
    {
        //Fire the event to BackgroundWorker to change the image
        m_FinishEvent.Set();
        timerFade.Enabled = false;
    }
    //Refresh the screen
    this.Invalidate();
}

Download and Run the Program

You can download and run SlideShow.exe, drag the images into the Windows Form, it will play the slideshow automatically. When you want to exit the slideshow, please press "Esc" or double click the form to start or stop the slideshow.

Points of Interest

Think backward and enjoy a better visual effect. Cheers!

History

  • 5 Oct, 2007 - Created the first project

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect MouxIdea Limited
Hong Kong Hong Kong
1981 Born in Hong Kong
1996 Become Badminton Trainer
1997 Hong Kong's Return to China
1998 The Year After Hong Kong's Return to China
1999 The Year Before Millennium
2000 First touch of programming - ASP(guestbook)
2001 Outstanding Student Award - Computing Department
2002 Xcellence Developer Awards - Best Graphical Focused Application(Game) Award
2003 Microsoft MVP - .NET
2004 Be lost in Technology
2005 Microsoft MVP - C#
2006 Microsoft MVP - C#
2007 Getting Marry - Cheers~
2008 Microsoft MVP - C#
2009 Microsoft MVP - C#
2010 Microsoft MVP - C#
2011 Start my software hut

http://www.csharpfans.com


http://www.bugyiu.com


http://www.mouxidea.com

Comments and Discussions

 
QuestionAdd image on load! Pin
Peeping10-Oct-17 22:01
Peeping10-Oct-17 22:01 
GeneralMy vote of 5 Pin
FernandoUY26-Dec-11 5:51
professionalFernandoUY26-Dec-11 5:51 
GeneralMy vote of 1 Pin
aslanshiva14-Jun-11 1:31
aslanshiva14-Jun-11 1:31 
GeneralMy vote of 1 Pin
behzad200023-Nov-09 9:00
behzad200023-Nov-09 9:00 
GeneralWIndows CE Pin
Win32nipuh16-Oct-07 7:09
professionalWin32nipuh16-Oct-07 7:09 
GeneralRe: WIndows CE [modified] Pin
Jacky Yiu18-Oct-07 23:50
Jacky Yiu18-Oct-07 23:50 
GeneralRe: WIndows CE Pin
Win32nipuh19-Oct-07 3:34
professionalWin32nipuh19-Oct-07 3:34 
GeneralRe: WIndows CE Pin
Jacky Yiu20-Oct-07 8:23
Jacky Yiu20-Oct-07 8:23 
GeneralLoadin new Image Pin
Bavario11-Oct-07 2:51
Bavario11-Oct-07 2:51 
GeneralRe: Loadin new Image Pin
Jacky Yiu12-Oct-07 3:26
Jacky Yiu12-Oct-07 3:26 
GeneralRe: Loadin new Image Pin
Bavario12-Oct-07 4:54
Bavario12-Oct-07 4:54 
GeneralRe: Loadin new Image Pin
Jacky Yiu12-Oct-07 5:16
Jacky Yiu12-Oct-07 5:16 
GeneralRe: Loadin new Image Pin
Jacky Yiu12-Oct-07 5:24
Jacky Yiu12-Oct-07 5:24 
GeneralUse WPF Pin
NormDroid5-Oct-07 2:11
professionalNormDroid5-Oct-07 2:11 
GeneralRe: Use WPF Pin
Jacky Yiu5-Oct-07 6:50
Jacky Yiu5-Oct-07 6:50 
GeneralRe: Use WPF Pin
MVP_KenLin@HK5-Nov-07 22:49
MVP_KenLin@HK5-Nov-07 22:49 
GeneralRe: Use WPF Pin
Jacky Yiu6-Nov-07 5:35
Jacky Yiu6-Nov-07 5:35 
GeneralThis #$%*# drop down explorer! Pin
dethtroll5-Oct-07 0:28
dethtroll5-Oct-07 0:28 
GeneralRe: This #$%*# drop down explorer! Pin
bryh8-Oct-07 13:45
bryh8-Oct-07 13:45 
GeneralRe: This #$%*# drop down explorer! Pin
Jacky Yiu8-Oct-07 17:33
Jacky Yiu8-Oct-07 17:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.