开发者

How Do I Create a System.Drawing.Icon with Multiple Sizes/Images?

I would like to create a single System.Drawing.Icon programmatically from 32x32, 16x16 Bitmaps. Is this po开发者_JAVA技巧ssible? If I load an icon with -

Icon myIcon = new Icon(@"C:\myIcon.ico");

...it can contain multiple images.


An .ico file can have multiple images in it, but when you load an .ico file and create an Icon object, only one of those images is loaded. Windows chooses the most appropriate image based on the current display mode and system settings and uses that one to initialize the System.Drawing.Icon object, ignoring the others.

So you can't create a System.Drawing.Icon with multiple images, you have to pick one before you create the Icon object.

Of course, It is possible to create an Icon at runtime from a bitmap, is that what you are really asking? Or are you asking how to create an .ico file?


You could try using png2ico to create a .ico file, invoking it using System.Diagnostics.Process.Start. You would need to create your images and save them to disc before invoking png2ico.


There's a nice code snippet here. It uses the Icon.FromHandle method.

From the link:

/// <summary>
/// Converts an image into an icon.
/// </summary>
/// <param name="img">The image that shall become an icon</param>
/// <param name="size">The width and height of the icon. Standard
/// sizes are 16x16, 32x32, 48x48, 64x64.</param>
/// <param name="keepAspectRatio">Whether the image should be squashed into a
/// square or whether whitespace should be put around it.</param>
/// <returns>An icon!!</returns>
private Icon MakeIcon(Image img, int size, bool keepAspectRatio) {
  Bitmap square = new Bitmap(size, size); // create new bitmap
  Graphics g = Graphics.FromImage(square); // allow drawing to it

  int x, y, w, h; // dimensions for new image

  if(!keepAspectRatio || img.Height == img.Width) {
    // just fill the square
    x = y = 0; // set x and y to 0
    w = h = size; // set width and height to size
  } else {
    // work out the aspect ratio
    float r = (float)img.Width / (float)img.Height;

    // set dimensions accordingly to fit inside size^2 square
    if(r > 1) { // w is bigger, so divide h by r
      w = size;
      h = (int)((float)size / r);
      x = 0; y = (size - h) / 2; // center the image
    } else { // h is bigger, so multiply w by r
      w = (int)((float)size * r);
      h = size;
      y = 0; x = (size - w) / 2; // center the image
    }
  }

  // make the image shrink nicely by using HighQualityBicubic mode
  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  g.DrawImage(img, x, y, w, h); // draw image with specified dimensions
  g.Flush(); // make sure all drawing operations complete before we get the icon

  // following line would work directly on any image, but then
  // it wouldn't look as nice.
  return Icon.FromHandle(square.GetHicon());
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜