Céd*_*vin 0 c# graphics combobox drawimage winforms
当项目被选中时,我尝试从组合框中的图像列表中绘制图像。
我能够绘制图像,但是当onSelctedIndexChanged活动结束时,我丢失了图像。
我的组合框已经有了 DrawMode.OwnerDrawFixed
我有一个ListImage名为 ImageList的控件,其中包含 10 张图片。
对于我的简短示例,我只需要在我的组合框中绘制 ImageList 位置 1 处的图像,这就是为什么我得到 this.ImageList.Draw(g, 0, 0, 1 );
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
if (this.SelectedIndex > -1)
{
var g = this.CreateGraphics();
this.ImageList.Draw(g, 0, 0, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
可能我没有依附于正确的事件。有什么建议吗?
在 Draw 之后的 IndexChanged 中有一个断点,请参见下图。它的工作,但我失去了我的事件后的形象。
将 ComboBox DrawMode更改为OwnerDrawVariable.
使用DrawItem事件从 ComboBox 项边界内的源(在本例中为 ImageList)绘制图像。
如果 ComboBox DropDownStyle设置为DropDownList,则图像将显示在选择框中;如果设置为DropDown,则只会绘制文本。
这里,Focus 矩形仅在鼠标点悬停在 ListControl 的项上时才绘制,而在选择项时不使用它,这由以下因素决定:
(e.State.HasFlag(DrawItemState.Focus) && !e.State.HasFlag(DrawItemState.ComboBoxEdit))。
// These could be properties used to customize the ComboBox appearance
Color cboForeColor = Color.Black;
Color cboBackColor = Color.WhiteSmoke;
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0) return;
Color foreColor = e.ForeColor;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
if (e.State.HasFlag(DrawItemState.Focus) && !e.State.HasFlag(DrawItemState.ComboBoxEdit)) {
e.DrawBackground();
e.DrawFocusRectangle();
}
else {
using (Brush backgbrush = new SolidBrush(cboBackColor)) {
e.Graphics.FillRectangle(backgbrush, e.Bounds);
foreColor = cboForeColor;
}
}
using (Brush textbrush = new SolidBrush(foreColor)) {
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),
e.Font, textbrush, e.Bounds.Height + 10, e.Bounds.Y,
StringFormat.GenericTypographic);
}
e.Graphics.DrawImage(this.imageList1.Images[e.Index],
new Rectangle(e.Bounds.Location,
new Size(e.Bounds.Height - 2, e.Bounds.Height - 2)));
}
Run Code Online (Sandbox Code Playgroud)
这里的幻数( 10, -2) 只是偏移量:
e.Bounds.Height + 10 =>图像右侧 10 个像素。
e.Bounds.Height -2 => 2 像素小于item.Bounds.Height.
| 归档时间: |
|
| 查看次数: |
1374 次 |
| 最近记录: |