Domanda

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

È stato utile?

Soluzione

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);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top