How do you draw an icon in grayscale?

B

Benny Raymond

I've written a class that inherits from MenuItem which displays icons
next to the items in a menu... The only problem I'm having is that I
have no clue how to turn these icons greyscale if they're item is
disabled. Right now I'm turning the text grey and would like to also
grey out the icon. Any help would be awesome. here's my code for
drawing the icon:


if ( this._icon != null )
{
if ( this.Text != "" && this.Text != "X" )
e.Graphics.DrawIcon(this._icon, e.Bounds.Left+ICON_PAD_LEFT,
e.Bounds.Top+ICON_PAD_TOP);
else
e.Graphics.DrawIcon(this._icon, e.Bounds.Left + ((e.Bounds.Width -
this._icon.Width) / 2), e.Bounds.Top+ICON_PAD_TOP); // center the icon
}
 
B

Benny Raymond

I found the ControlPaint class... however i'm now wondering:
Would this be bad? I'm not sure if it's going to leak memory or not -
can I get some feedback? thanks :)

if (this._icon != null)
{
if (this.Text != "" && this.Text != "X")
{
if (this.Enabled)
e.Graphics.DrawIcon(this._icon, e.Bounds.Left+ICON_PAD_LEFT,
e.Bounds.Top+ICON_PAD_TOP);
else
ControlPaint.DrawImageDisabled(e.Graphics, this._icon.ToBitmap(),
e.Bounds.Left+ICON_PAD_LEFT, e.Bounds.Top+ICON_PAD_TOP, br.Color);
}
else
{
// center icon:
if (this.Enabled)
e.Graphics.DrawIcon(this._icon, e.Bounds.Left +
((e.Bounds.Width - this._icon.Width) / 2), e.Bounds.Top+ICON_PAD_TOP);
else
ControlPaint.DrawImageDisabled(e.Graphics, this._icon.ToBitmap(),
e.Bounds.Left + ((e.Bounds.Width - this._icon.Width) / 2),
e.Bounds.Top+ICON_PAD_TOP, br.Color);
}
}
 
B

Bob Powell [MVP]

I don't see anything wrong with your solution. GC will take care of the
bitmap. If you want to be really belt-and-braces you could do something
like:

Bitmap bm=icon.tobitmap;
ControlPaint.DrawImageDisabled(...);
bm.Dispose();

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
B

Benny Raymond

Awesome, thanks...

Lately I've been realy cautious because back when I didn't understand
drawing quite as much, I had a function that was leaking about 20mb a
second... ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top