为ListView项添加边框(仅在图像周围)

时间:2016-04-06 09:01:03

标签: c# winforms

我发现这个question提供了有关如何为ListView项添加边框的解决方案:

enter image description here

但我只想在图像周围添加边框,如下所示:

enter image description here

可以这样做吗?

1 个答案:

答案 0 :(得分:3)

假设LargeIcon View模式,图片被居中,而他们的Size位于相关的LargeImageList.ImageSize中,所以这样的事情应该是工作:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
    Size sz = listView1.LargeImageList.ImageSize;
    int w = sz.Width + 4;
    int h = sz.Height + 3;
    int x = (e.Bounds.Width - sz.Width) / 2 + e.Bounds.X - 2;
    int y = e.Bounds.Top + 1 ;
    using (Pen pen = new Pen(Color.Red, 2f))
    {
        pen.Alignment = PenAlignment.Center;
        e.Graphics.DrawRectangle(pen, x, y, w, h);
    }     
}

这是我的ListView

enter image description here

当然,如果您希望框架超过整个宽度(e.Bounds.Width),您只需限制高度,如图所示..:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
  e.DrawDefault = true;
  Size sz = listView1.LargeImageList.ImageSize;
  e.Graphics.DrawRectangle(Pens.Red, e.Bounds.X,e.Bounds.Y, e.Bounds.Width,sz.Height + 2);
}

enter image description here

如果你想让当前关注的项目脱颖而出,你可以这样做:

Color bCol = e.State.HasFlag(ListViewItemStates.Focused) ?
    Color.LightBlue : listView1.BackColor;
using (SolidBrush brush = new SolidBrush(bCol))
    e.Graphics.FillRectangle(brush, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, sz.Height + 2);
在绘制矩形之前

enter image description here

或者您可以根据项目状态选择矩形的颜色。