[英]Selecting the size of a System.Drawing.Icon?
我有一個圖標,它有幾種不同的大小(16px、32px、64px)。 我正在調用ToBitmap()
,但它總是返回 32px 圖像。 我如何檢索 64px 一個?
這有幫助嗎?
Icon sizedIcon = new Icon(Resources.ResourceIcon, new Size(64,64));
對於遇到同樣問題的其他人,我找到了一個不錯的小解決方案。
Image img = new Icon(Properties.Resources.myIcon, width, height).ToBitmap()
這是 ResourceManager 類中相當痛苦的限制。 它的 GetObject() 方法沒有提供一種方法來傳遞允許按大小選擇返回圖標的額外參數。 一種解決方法是將圖標添加到項目中。 使用 Project + Add Existing Item,選擇您的 .ico 文件。 選擇添加的圖標並將 Build Action 屬性更改為“Embedded Resource”。
您現在可以使用如下代碼檢索所需的圖標:
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");
}
示例用法:
var icon1 = GetIconFromEmbeddedResource("ARW04LT", new Size(16, 16));
var icon2 = GetIconFromEmbeddedResource("ARW04LT", new Size(32, 32));
注意一種可能的故障模式:此代碼假定圖標已添加到包含該方法的同一程序集中。
下面設置工具欄中所有按鈕的圖標大小。
它依賴於存儲在按鈕標簽中的資源名稱。
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();
}
}
}
internal static class IconHelper {
public static Icon GetSize(this Icon icon, int width, int height) {
return icon.GetSize(new Size(width, height));
}
public static Icon GetSize(this Icon icon, Size size) {
using(var mem = new MemoryStream()) {
icon.Save(mem);
mem.Position = 0;
return new Icon(mem, size);
}
}
}
大小是在您第一次創建Icon
實例時確定的,因此您需要在創建它時指定要使用的大小,使用帶有Size
參數的Icon
構造函數之一。
.Net 框架中沒有執行此操作的內置方法。
相反,您可以使用這個庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.