简体   繁体   中英

Display image in ComboBox

I'm using the following code to display image representing a color in a combobox as per this SO answer https://stackoverflow.com/a/13385209/848968 I have added the custom control to the form,but i cannot figure out how to add items with images to it.Kindly advice.

  public sealed class ColorSelector : ComboBox
    {
        public ColorSelector()
        {
            DrawMode = DrawMode.OwnerDrawFixed;
            DropDownStyle = ComboBoxStyle.DropDownList;
        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            e.DrawBackground();

            e.DrawFocusRectangle();

            if (e.Index >= 0 && e.Index < Items.Count)
            {
                DropDownItem item = (DropDownItem)Items[e.Index];

                e.Graphics.DrawImage(item.Image, e.Bounds.Left, e.Bounds.Top);

                e.Graphics.DrawString(item.Value, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left + item.Image.Width, e.Bounds.Top + 2);
            }

            base.OnDrawItem(e);
        }
    }

public sealed class DropDownItem
{
    public string Value { get; set; }

    public Image Image { get; set; }

    public DropDownItem()
        : this("")
    { }



 public DropDownItem(string val)
    {
        Value = val;
        Image = new Bitmap(16, 16);
        using (Graphics g = Graphics.FromImage(Image))
        {
            using (Brush b = new SolidBrush(Color.FromName(val)))
            {
                g.DrawRectangle(Pens.White, 0, 0, Image.Width, Image.Height);
                g.FillRectangle(b, 1, 1, Image.Width - 1, Image.Height - 1);
            }
        }
    }

    public override string ToString()
    {
        return Value;
    }
}

Based on your requirement, I have modified OnDrawItem method and changed the comboBox width and height to clear image visible

Please find the code below

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        if (e.Index >= 0  )
        {
            e.DrawBackground();
            e.DrawFocusRectangle();

            string imageFilePath = @Items[e.Index].ToString();;
            int width = 40;
            int height = 20;

            Image img = Image.FromFile(imageFilePath);
            e.Graphics.DrawImage(img, 0, e.Bounds.Top + 2, width, height);
            e.Graphics.DrawString(imageFilePath, e.Font, new
                    SolidBrush(e.ForeColor), e.Bounds.Left + width, e.Bounds.Top + 2);
            base.OnDrawItem(e);
        }

    }

}

output :

见附图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM