ListView大图标垂直对齐图像

时间:2012-08-22 11:20:20

标签: c# .net winforms listview imagelist

我有ViewView类型为LargeIcon的ListView。 ListView已分配LargeImageList。指定的ImageList具有ImageSize 200x200。 将添加到ImageList的图像的大小与200x200 ImageList大小不匹配。它们可以具有较小的宽度或高度。在这两种情况下,我希望图像按中心对齐,即Winforms.Label类的

1 个答案:

答案 0 :(得分:3)

ImageList将调整图像大小以适合ImageSize。要使图像保持原始大小并居中,您需要创建具有所需属性的新图像。执行此操作的示例代码(未经测试):

public static void AddCenteredImage(ImageList list, Image image) {
    using (var bmp = new Bitmap(list.ImageSize.Width, list.ImageSize.Height))
    using (var gr = Graphics.FromImage(bmp)) {
        gr.Clear(Color.Transparent);   // Change background if necessary
        var size = image.Size;
        if (size.Width > list.ImageSize.Width || size.Height > list.ImageSize.Height) {
            // Image too large, rescale to fit the image list
            double wratio = list.ImageSize.Width / size.Width;
            double hratio = list.ImageSize.Height / size.Height;
            double ratio = Math.Min(wratio, hratio);
            size = new Size((int)(ratio * size.Width), (int)(ratio * size.Height));
        }
        var rc = new Rectangle(
            (list.ImageSize.Width - size.Width) / 2,
            (list.ImageSize.Height - size.Height) / 2,
            size.Width, size.Height);
        gr.DrawImage(image, rc);
        list.Images.Add(bmp);
    }
}