Question

What is the best (least resource heavy) way to fade an image in and out every 20 seconds with a duration of 1 second, against a black background (screensaver), in C# ?

(an image about 350x130px).

I need this for a simple screensaver that's going to run on some low level computers (xp).

Right now I'm using this method against a pictureBox, but it is too slow:

    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;
    }
Was it helpful?

Solution

You could probably use a Color Matrix like in this example on msdn

http://msdn.microsoft.com/en-us/library/w177ax15%28VS.71%29.aspx

OTHER TIPS

Instead of using a Pen and the DrawLine() method, you can use Bitmap.LockBits to access the memory of your image directly. Here's a good explanation of how it works.

Put a Timer on your form, and in the constructor, or the Form_Load, write

    timr.Interval = //whatever interval you want it to fire at;
    timr.Tick += FadeInAndOut;
    timr.Start();

Add a private method

private void FadeInAndOut(object sender, EventArgs e)
{
    Opacity -= .01; 
    timr.Enabled = true;
    if (Opacity < .05) Opacity = 1.00;
}

Here's my take on this

    private void animateImageOpacity(PictureBox control)
    {
        for(float i = 0F; i< 1F; i+=.10F)
        {
            control.Image = ChangeOpacity(itemIcon[selected], i);
            Thread.Sleep(40);
        }
    }

    public static Bitmap ChangeOpacity(Image img, float opacityvalue)
    {
        Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image
        Graphics graphics = Graphics.FromImage(bmp);
        ColorMatrix colormatrix = new ColorMatrix {Matrix33 = opacityvalue};
        ImageAttributes imgAttribute = new ImageAttributes();
        imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
        graphics.Dispose();   // Releasing all resource used by graphics 
        return bmp;
    }

It's also recommended to create another thread because this will freeze your main one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top