Как создать System.Drawing.Icon с несколькими размерами / изображениями? - PullRequest
10 голосов
/ 01 февраля 2010

Я хотел бы создать один System.Drawing.Icon программно из растровых изображений 32x32, 16x16. Это возможно? Если я загружаю значок с -

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

... может содержать несколько изображений.

Ответы [ 3 ]

7 голосов
/ 01 февраля 2010

Файл .ico может содержать несколько изображений, но при загрузке файла .ico и создании объекта Icon загружается только одно из этих изображений. Windows выбирает наиболее подходящее изображение на основе текущего режима отображения и системных настроек и использует его для инициализации объекта System.Drawing.Icon, игнорируя остальные.

Таким образом, вы не можете создать System.Drawing.Icon с несколькими изображениями, вам нужно выбрать одно, прежде чем создавать объект Icon.

Конечно, можно создать Icon во время выполнения из растрового изображения, это то, что вы действительно спрашиваете? Или вы спрашиваете, как создать .ico файл?

0 голосов
/ 01 февраля 2010

Вы можете попробовать использовать png2ico для создания .ico-файла, вызывая его с помощью System.Diagnostics.Process.Start. Вам нужно будет создать свои изображения и сохранить их на диск перед вызовом png2ico.

0 голосов
/ 01 февраля 2010

Здесь есть хороший фрагмент кода . Используется метод 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());
} 
...