[英]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.我正在使用以下代码根据此 SO 答案在组合框中显示表示颜色的图像https://stackoverflow.com/a/13385209/848968我已将自定义控件添加到表单中,但我不知道如何将带有图像的项目添加到 it.Kindly 建议。
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根据您的要求,我修改了 OnDrawItem 方法并将组合框的宽度和高度更改为清晰可见的图像
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 :输出 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.