ET.
ET.

Reputation: 1969

Displaying same icon in 2 different sizes on c#

My goal is to display the same icon twice, but each time in different size. I tried the following:

FileStream fs = new FileStream("name_of_the_icon_file.ico", FileMode.Open);
Icon ico = new Icon(fs, 32, 32);     //create an in-memory instance of the icon, size 32x32
Icon ico2 = new Icon(fs, 16, 16);   //create an in-memory instance of the icon, size 16x16  
...
Graphics.DrawIcon(ico, /*some point*/);
Graphics.DrawIcon(ico2, /*some other point*/);

The last line throws an ArgumentException: Value does not fall within the expected range. Can some one explain me whats wrong and whats the way to do this right?

Upvotes: 0

Views: 2067

Answers (1)

Jason Williams
Jason Williams

Reputation: 57892

An icon file contains one or more images of different sizes.

The Icon constructor you are using tries to find an exact match for the size you have given in the icon file. If the icon file does not contain a 16x16 image, it will throw an exception as it can't match that exact size.

Instead, just load the icon (without specifying a size, so that all sizes are loaded) and then use the Graphics.DrawIcon(icon, rectangle) override to draw it at the size you wish it to stretch into. It will render using the best-match size defined within the icon (and then scale it if necessary).

For best quality, edit your icon file (I suggest using IcoFX) to supply specific images at the sizes you want (32x32 and 16x16) so that the icons are not scaled when you draw them.

Upvotes: 2

Related Questions