Solved

Fading Between Colors

Posted on 2006-07-12
10
559 Views
Last Modified: 2008-01-09
I have a program in which I need to fade between two colors (to create a mouse over effect). Drawing is performed by a ColorBlend object and a LinearGradientBrush with its InterpolationColors property. The control I am writing should fade from one set of colors (in an array) to another, with a float parameter from 0.0f (use the first color) to 1.0f (use the second color). I have written code to do this by using a temporary bitmap object and drawing to it, however I have found this method to be quite slow...

I'm looking for a faster method to replace the one below that will take the same parameters and function in the same way to fade between two arrays of colors. Below is the code for my current method:


        internal static Color[] GetFadeColors(Color[] Original, Color[] New, float Progress)
        {
            if (Original.Length != New.Length)
            {
                throw new Exception("Parameters Incorrect: Original & New Color Arrays Must Have Same Length");
            }

            Color[] ret = new Color[Original.Length];

            Bitmap tmp = new Bitmap(1, Original.Length);
            Graphics g = Graphics.FromImage(tmp);

            int alpha = (int)(Progress * 255);

            for (int i = 0; i < Original.Length; i++)
            {
                Pen p = new Pen(Original[i]);
                g.DrawLine(p, 0, i, 1, i);
                p.Dispose();

                Color newcolor = Color.FromArgb(alpha, New[i]);
                p = new Pen(newcolor);
                g.DrawLine(p, 0, i, 1, i);
                p.Dispose();

                ret[i] = tmp.GetPixel(0, i);
            }

            g.Dispose();
            tmp.Dispose();

            return ret;
        }
0
Comment
Question by:paulb1989
  • 5
  • 5
10 Comments
 
LVL 5

Author Comment

by:paulb1989
ID: 17093276
If it matters, the color arrays will typically have 4 or 5 colors in them, but it could increase in the future so I don't want the method to be reliant on the amount of items in the arrays.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17093315
I was wondering if HLS (Hue-Luminance-Saturation) functions might help.  Here is a VB.NET class that we can duplicate in C#, if it applies to your situation:

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21633738.html

Bob
0
 
LVL 5

Author Comment

by:paulb1989
ID: 17093459
But I'm not just lightening and darkening colors, the two colors can be completely different
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17093676
It not just lightening and darkening, but affecting color values, but I see your point, which is why I asked before continuing.  

There is also color transformations in GDI+, if that might prove to be useful:

GDI+ Graphics Transformation
http://www.awprofessional.com/articles/article.asp?p=102607&seqNum=8&rl=1

It looks like you are drawing a progress bar that has a color transform from one end of the bar to the other.

Bob
0
 
LVL 5

Author Comment

by:paulb1989
ID: 17093751
I'm not drawing a progress bar, I'm writing controls that immitate the office 2007 ribbon style. This code is used to fade in the colors that are used when the mouse is over a control (button, tab, etc) so that rather than just skipping from its normal look to its mouse over look, the control fades the mouse over look in, slowly (well, currently too slowly) changing from the normal colors to the colors used when the mouse is over the object.

As for the GDI+ link, I don't see anything about blending two colors to fade between them as I am doing, just ways to modify one color in a specific way. My code needs to take two colors and combine them to give back a color that is part way between the original color and the new color, when the colors are completely different (eg, typically the colors are moving from shades of blue to orange, or dark grays to orange).
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 17093859
>>the control fades the mouse over look in, slowly (well, currently too slowly)
Very good points.  I wasn't getting the implication of the color blend (it's been a long day).  

What is driving the slowly part?  Is there a timer or some other kind of similar method?

Bob
0
 
LVL 5

Author Comment

by:paulb1989
ID: 17093917
I have a timer set to fire every 50ms which increments the progress value by 0.1f each time, so in theory it should take 500ms to go from the original colors through to the new colors, but it actually takes around a second (may not sound like much but its noticeably slow).
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 125 total points
ID: 17094011
Obvious question:  Have you experimented with the increment value to see what the "best" value is?

Bob
"Mr. Obvious"
0
 
LVL 5

Author Comment

by:paulb1989
ID: 17094048
OK I just tried incrementing by 0.2f and it does look a lot better, so unless anyone posts a more efficient method of fading the colors in the next few hours or so (I'm sure there must be a more efficient way than drawing to a bitmap), the points are yours. Otherwise they'll be split.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17094180
There are probably faster ways of getting information from the bitmap other than using GetPixel call, like using Scan0 + Stride.

Here is an example of what I mean:

Converting an RGB image to 1 bit-per-pixel monochrome.
http://www.bobpowell.net/onebit.htm

         Bitmap img = (Bitmap)Image.FromFile(dlg.FileName);
        //Ensure that it's a 32 bit per pixel file
        if(img.PixelFormat!=PixelFormat.Format32bppPArgb)
        {
          Bitmap temp=new Bitmap(img.Width,img.Height,PixelFormat.Format32bppPArgb);
          Graphics g=Graphics.FromImage(temp);
          g.DrawImage(img, new Rectangle(0,0,img.Width,img.Height),0,0,img.Width,img.Height,GraphicsUnit.Pixel);
          img.Dispose();
          g.Dispose();
          img=temp;
        }

        this.pictureBox1.Image=img;
        //lock the bits of the original bitmap
        BitmapData bmdo=img.LockBits(new Rectangle(0,0,img.Width,img.Height),ImageLockMode.ReadOnly,img.PixelFormat);
 
        //and the new 1bpp bitmap
        bm=new Bitmap(this.pictureBox1.Image.Width,this.pictureBox1.Image.Height,PixelFormat.Format1bppIndexed);
        BitmapData bmdn=bm.LockBits(new Rectangle(0,0,bm.Width,bm.Height),ImageLockMode.ReadWrite,PixelFormat.Format1bppIndexed);
 
        //for diagnostics
        DateTime dt=DateTime.Now;
       
        //scan through the pixels Y by X
        int x,y;
        for(y=0;y<img.Height;y++)
        {
          for(x=0;x<img.Width;x++)
          {
            //generate the address of the colour pixel
            int index=y*bmdo.Stride+(x*4);
            //check its brightness
            if(Color.FromArgb(Marshal.ReadByte(bmdo.Scan0,index+2),
                            Marshal.ReadByte(bmdo.Scan0,index+1),
                            Marshal.ReadByte(bmdo.Scan0,index)).GetBrightness()>0.5f)
              this.SetIndexedPixel(x,y,bmdn,true); //set it if its bright.
          }
        }
 
        //tidy up
        bm.UnlockBits(bmdn);
        img.UnlockBits(bmdo);
 
        //show the time taken to do the conversion
        TimeSpan ts=dt-DateTime.Now;
        System.Diagnostics.Trace.WriteLine("Conversion time was:"+ts.ToString());
 
        //display the 1bpp image.
        this.pictureBox2.Image=bm;

Bob
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
XML & .net 5 41
Definitions and default visual studio colors 5 58
how to read json value 2 31
SQL Exceptions 3 39
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now