Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c# - Draw border for image in listview

On a treeview after the select event, I populate a listview with images.
I want to custom format these images and place a black color border around each image.

   private void TreeView1_Select(object sender, EventArgs e) {
        if (folder != null && System.IO.Directory.Exists(folder)) {

            DirectoryInfo dir = new DirectoryInfo(@folder);
            foreach (FileInfo file in dir.GetFiles()) {
                try {
                    imageList.Images.Add(Image.FromFile(file.FullName));
                } catch {
                    Console.WriteLine("This is not an image file");
                }
            }

            for (int j = 0; j < imageList.Images.Count; j++) {
                this.ListView1.Items.Add("Item" + j);
                this.ListView1.Items[j].ImageIndex = j;
            }

            this.ListView1.View = View.LargeIcon;
            this.ListView1.LargeImageList = imageList;
            this.ListView1.DrawItem += 
                new DrawListViewItemEventHandler(ListView1_DrawItem);

        }
    }

    private void ListView1_DrawItem(object sender, DrawListViewItemEventArgs e) 
    {

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would add a border using a Graphics object immediately after loading the images from file:

EDIT: modified the code, this works for me...

    private void TreeView1_Select(object sender, EventArgs e) {
        if (folder != null && System.IO.Directory.Exists(folder)) {

            DirectoryInfo dir = new DirectoryInfo(@folder);
            foreach (FileInfo file in dir.GetFiles()) {

                Image img = new Bitmap(Image.FromFile(file.FullName));
                using (Graphics g = Graphics.FromImage(img)){
                    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
                }
                imageList.Images.Add(img);

NOTE: the image copying is intended; if I modify the code to

    Image img = (Bitmap)Bitmap.FromFile("test.bmp");

as suggested in the comments, I get an exception saying "A Graphics object cannot be created from an image that has an indexed pixel format."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...