c# - 如何为图像列表中的多个图标使用单个位图? (不将其拆分为多个文件)

标签 c# .net winforms

我有一个包含 24x24 图标的位图。我想在工具条的图像列表中使用它。是否可以使用位图并根据 ToolStripButton 的 ImageIndex 选择它的正确部分?我想避免将它拆分成多个文件。

最佳答案

您可以继承 ToolStripButton 并为图像提供新的来源。这是一个相当简单的方法;您可能需要根据您的确切需求扩展这个想法。

    public class ToolStripImageButton: ToolStripButton
{
    public ToolStripImageButton()
        : base()
    {
    }


    private Image iconMap;
    private Int32 iconMapIndex;

    [RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
    public Image IconMap
    {
        get { return this.iconMap; }
        set
        {
            this.iconMap = value;
            this.RecalculateImage();
        }
    }
    [RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
    public Int32 IconMapIndex
    {
        get { return this.iconMapIndex; }
        set
        {
            this.iconMapIndex = value;
            this.RecalculateImage();
        }
    }

    protected void RecalculateImage()
    {
        if (base.Image != null)
        {
            base.Image.Dispose();
            base.Image = null;
        }
        if (this.iconMap != null)
        {
            // assumes each icon is 16x16, you could add more properties for flexibility
            Int32 x = this.iconMap.Width / 16;
            Int32 y = this.iconMap.Width / 16;

            Int32 iconCount = x * y;
            if (this.iconMapIndex < 0 || this.iconMapIndex >= iconCount) return;

            Int32 offsetX = (this.iconMapIndex % x) * 16;
            Int32 offsetY = (this.iconMapIndex / x) * 16;

            Bitmap bitmap = new Bitmap(16, 16);
            using (Graphics g = Graphics.FromImage(bitmap))

            g.DrawImage(
                this.iconMap,
                new Rectangle(0,0,bitmap.Width,bitmap.Height), 
                new Rectangle(offsetX, offsetY, bitmap.Width, bitmap.Height), 
                    GraphicsUnit.Pixel);

            base.Image = bitmap;
        }
    }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override Image Image
    {
        get
        {
            return base.Image;
        }
        set
        {
            // ignore
        }
    }

关于c# - 如何为图像列表中的多个图标使用单个位图? (不将其拆分为多个文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9785221/

相关文章:

.net - 什么时候需要接口(interface)?

winforms - Datagridview 列宽

c# - 不再在 docker 中使用 dotnet watch 的理由是什么

c# - C# 的 VB.NET 等价物是什么?运算符(operator)?

c# - 如果数据库中不存在值,如何在sql查询中返回错误消息

c# - 在 .NET 应用程序中处理音频的推荐方法?

c# - 在 C# winform 中在运行时更改语言

c# - 如何将 Windows 窗体应用程序 (C#) 制作成单个 exe 文件?

c# - 部分 View 未正确呈现

c# - 使用 twilio c# 客户端传回 twilio 响应