zabulus
zabulus

Reputation: 2523

ListView Larget Icon vertical alignment of the images

I have ListView with the View type LargeIcon. The ListView has assigned LargeImageList. The assigned ImageList has ImageSize 200x200. Images that will be added to the ImageList have size that doesn't match to 200x200 ImageList size. They can have a lesser width or height. In both cases I want images to be aligned by center, i.e. MiddleCenter property for Winforms.Label class

Upvotes: 1

Views: 2131

Answers (1)

Hans Passant
Hans Passant

Reputation: 942328

ImageList will resize the image to fit the ImageSize. To get the image at its original size, and centered, you'll need to create a new image with the desired properties. Sample code to do this (untested):

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);
    }
}

Upvotes: 3

Related Questions