2010-02-01 29 views

回答

7

一個.ico文件可以有多個圖像,但是當你加載一個.ico文件,並創建一個圖標對象,只有一個圖像加載。 Windows會根據當前的顯示模式和系統設置選擇最合適的圖像,並使用該圖像初始化對象,而忽略其他圖像。

所以你不能創建一個System.Drawing.Icon與多個圖像,你必須選擇一個,然後再創建Icon對象。

當然,可以在運行時從位圖創建一個圖標,這是你真正想問什麼?或者你問如何創建一個.ico文件?

+1

圖標但如果我加載.ico文件就像我上面顯示,我可以訪問16×32×32,48×48等這樣的 - : 圖標smallIcon =新圖標(myIcon,16,16); – Damien 2010-02-01 03:51:45

+2

因爲它知道圖標是從哪個文件/資源​​創建的,可以返回並獲取新圖像。雖然沒有辦法將圖像添加到圖標對象。 – 2010-02-01 04:22:03

+0

@JohnKnoeller其實,這不是真的。所有的圖像數據都由'Icon'類加載到內存中,當您從另一個'Icon'對象調整大小時,圖像數據將被共享並從原始(共享)數據中拉出最近的尺寸。 – NetMage 2018-01-11 18:12:14

0

有一個不錯的code snippet here。它使用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()); 
} 
+3

我認爲他想創建多個圖像...... – 2010-02-01 03:20:26

0

您可以嘗試使用png2ico創建一個.ico文件,使用System.Diagnostics.Process.Start調用它。在調用png2ico之前,您需要創建圖像並將其保存到光盤。