Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the size of a System.Drawing.Icon?

I have a icon which has a few different sizes (16px, 32px, 64px). I am calling ToBitmap() on it, but it is always returning the 32px image. How do I retrieve the 64px one?

like image 951
Andy Hin Avatar asked Oct 26 '10 15:10

Andy Hin


4 Answers

Does this help?

Icon sizedIcon = new Icon(Resources.ResourceIcon, new Size(64,64));
like image 118
Stoio Avatar answered Oct 19 '22 00:10

Stoio


For anyone else stumbling upon the same problem, I've found a nice little solution.

Image img = new Icon(Properties.Resources.myIcon, width, height).ToBitmap()
like image 35
Netfangled Avatar answered Oct 19 '22 00:10

Netfangled


This is a fairly painful limitation in the ResourceManager class. Its GetObject() method doesn't provide a way to pass extra arguments that would allow selecting the returned icon by size. A workaround is to add the icon to the project instead. Use Project + Add Existing Item, select your .ico file. Select the added icon and change the Build Action property to "Embedded Resource".

You can now retrieve the desired icon with code like this:

    public static Icon GetIconFromEmbeddedResource(string name, Size size) {
        var asm = System.Reflection.Assembly.GetExecutingAssembly();
        var rnames = asm.GetManifestResourceNames();
        var tofind = "." + name + ".ICO";
        foreach (string rname in rnames) {
            if (rname.EndsWith(tofind, StringComparison.CurrentCultureIgnoreCase)) {
                using (var stream = asm.GetManifestResourceStream(rname)) {
                    return new Icon(stream, size);
                }
            }
        }
        throw new ArgumentException("Icon not found");
    }

Sample usage:

        var icon1 = GetIconFromEmbeddedResource("ARW04LT", new Size(16, 16));
        var icon2 = GetIconFromEmbeddedResource("ARW04LT", new Size(32, 32));

Beware one possible failure mode: this code assumes that the icon was added to the same assembly that contains the method.

like image 30
Hans Passant Avatar answered Oct 19 '22 01:10

Hans Passant


The following sets the icon size for all the buttons in the toolbar.
It relies on the resource name being stored in the button tag.

public void SetButtons(object toolstrip, int IconWidth, int IconHeight)
{
    var ts = (ToolStrip) toolstrip;
    var size = new System.Drawing.Size();
    size.Height = IconSize;
    size.Width = IconSize;

    foreach (ToolStripButton tsBtn in ts.Items)
    {
        tsBtn.ImageScaling = ToolStripItemImageScaling.None;
        var resourcename = (String) tsBtn.Tag;
        if (resourcename != null)
        {
            var myIcon = (Icon) Properties.Resources.ResourceManager.GetObject(resourcename);
            var newIcon = new Icon(myIcon, IconWidth, IconHeight);
            tsBtn.Image = newIcon.ToBitmap();
        }
    }
}
like image 3
Kirsten Avatar answered Oct 18 '22 23:10

Kirsten