我有一个图标,它有几个不同的尺寸(16px、32px、64px)。我使用 ToBitmap()
方法调用它,但它总是返回32px大小的图像。如何获取64px大小的图像?
我有一个图标,它有几个不同的尺寸(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()
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
构造函数。
ToBitmap()
方法。 - SLaks