1

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

4

1 回答 1

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);
    }
}
于 2012-08-22T13:04:37.620 回答