如何创建包含多个尺寸/图像的 System.Drawing.Icon?

10

我想通过32x32、16x16位图程序化创建一个单一的System.Drawing.Icon。这可行吗?如果我使用-加载一个图标

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

...它可以包含多张图片。

3个回答

8
一个ico文件中可以有多个图像,但是当你加载一个ico文件并创建一个Icon对象时,只会加载其中一个图像。Windows根据当前的显示模式和系统设置选择最合适的图像,并使用它来初始化System.Drawing.Icon对象,忽略其他图像。
因此,在创建Icon对象之前,你不能创建带有多个图像的System.Drawing.Icon。当然,你可以在运行时从位图创建一个Icon,这是你真正想问的吗?还是你想知道如何创建一个ico文件?

1
但是,如果我像上面展示的那样加载一个.ico文件,我可以像这样访问16x16、32x32、48x48等大小的图标:Icon smallIcon = new Icon(myIcon, 16, 16); - Damien
2
因为它知道图标是从哪个文件/资源创建的,并且可以返回并获取新图像。但是,没有办法向图标对象添加图像。 - John Knoeller
1
@JohnKnoeller 其实那并不是完全正确的。所有的图像数据都由 Icon 类加载到内存中,当你从另一个 Icon 对象调整大小时,图像数据会被共享,并从原始(共享的)数据中拉取最接近的尺寸。 - NetMage

0

这里有一个不错的代码片段。它使用了Icon.FromHandle方法。

来自链接:

/// <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
你可以尝试使用 png2ico 来创建.ico文件,使用 System.Diagnostics.Process.Start 调用它。在调用 png2ico 之前,您需要创建并将图像保存到磁盘上。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接