Click here to Skip to main content
Click here to Skip to main content
Go to top

Slide Show with Fade In/Out Effect

, 5 Oct 2007
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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:

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:

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)

Share

About the Author

Jacky Yiu
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

 
GeneralMy vote of 5 PinmemberFernandaUY26-Dec-11 5:51 
GeneralMy vote of 1 Pinmemberaslanshiva14-Jun-11 1:31 
GeneralMy vote of 1 Pinmemberbehzad200023-Nov-09 9:00 
GeneralWIndows CE PinmemberWin32nipuh16-Oct-07 7:09 
GeneralRe: WIndows CE [modified] PinmemberJacky Yiu18-Oct-07 23:50 
GeneralRe: WIndows CE PinmemberWin32nipuh19-Oct-07 3:34 
GeneralRe: WIndows CE PinmemberJacky Yiu20-Oct-07 8:23 
GeneralLoadin new Image PinmemberBavario11-Oct-07 2:51 
GeneralRe: Loadin new Image PinmemberJacky Yiu12-Oct-07 3:26 
GeneralRe: Loadin new Image PinmemberBavario12-Oct-07 4:54 
GeneralRe: Loadin new Image PinmemberJacky Yiu12-Oct-07 5:16 
GeneralRe: Loadin new Image PinmemberJacky Yiu12-Oct-07 5:24 
GeneralUse WPF Pinmembernorm .net5-Oct-07 2:11 
GeneralRe: Use WPF PinmemberJacky Yiu5-Oct-07 6:50 
GeneralRe: Use WPF PinmemberMVP_KenLin@HK5-Nov-07 22:49 
GeneralRe: Use WPF PinmemberJacky Yiu6-Nov-07 5:35 
GeneralThis #$%*# drop down explorer! Pinmembersotona5-Oct-07 0:28 
GeneralRe: This #$%*# drop down explorer! Pinmemberbryh8-Oct-07 13:45 
GeneralRe: This #$%*# drop down explorer! PinmemberJacky Yiu8-Oct-07 17:33 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 5 Oct 2007
Article Copyright 2007 by Jacky Yiu
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid