我正在按照此答案https://stackoverflow.com/a/13385209/848968使用以下代码在组合框中显示代表颜色的图像 我已经将自定义控件添加到了表单中,但是我不知道如何向其中添加带有图像的项目。敬请注意。
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;
}
}
答案 0 :(得分:0)
根据您的要求,我修改了OnDrawItem方法并更改了comboBox的宽度和高度以清除可见的图像
请在下面找到代码
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);
}
}
}
输出: