如何基于鼠标单击选择图片框上的图像

时间:2014-11-05 06:16:31

标签: c# .net winforms picturebox

我有4个图片框加载图片。我想基于鼠标点击选择这些图像。例如,如果我单击图片框1和2中的图像,我只想从这些图片框1和2中获取图像。该功能看起来像Android手机中的图库。

1 个答案:

答案 0 :(得分:0)

这不是很难。动态创建pictureBoxes,添加相同的Click处理程序并存储来自所选pictureBox的图像

e.g。画廊形式(最后一张图片被选中)

gallery form

public partial class GalleryForm : Form
{
    // stores selected images in order of adding
    private readonly List<Image> _gallery = new List<Image>();
    private readonly Random _rnd = new Random();

    // handle pics layout on form
    private readonly FlowLayoutPanel flowPanel;
    public GalleryForm()
    {
        InitializeComponent();

        Name = "GalleryForm";
        Text = "Gallery";
        ClientSize = new Size(276, 274);

        // flowPanel will contain picture boxes with images
        flowPanel = new FlowLayoutPanel();
        flowPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left| AnchorStyles.Right;
        flowPanel.Location = new Point(12, 12);
        flowPanel.Name = "flowPanel";
        flowPanel.Size = new Size(252, 250);

        int picsCount = 4;
        var picSize = new Size(100, 100);
        var imSize = new Size(50, 50);

        // creates required number of picture boxes with simple images
        for (int p = 0; p < picsCount; p++)
        {
            var picBox = new PictureBox();
            picBox.Name = "pic" + (p+1).ToString();
            picBox.Size = picSize;
            picBox.SizeMode = PictureBoxSizeMode.Zoom;
            picBox.Image = GetImage(p, imSize);
            picBox.Click += ClickOnImage;
            flowPanel.Controls.Add(picBox);
        }

        Controls.Add(flowPanel);
    }
    // click handler
    private void ClickOnImage(object sender, EventArgs eventArgs)
    {
        var picBox = (PictureBox) sender;
        if (_gallery.Remove(picBox.Image))
            // if _gallery contained image, remove selection
            picBox.BorderStyle = BorderStyle.None;
        else
        {          
            // add selection
            picBox.BorderStyle = BorderStyle.Fixed3D;
            // add image to _gallery
            _gallery.Add(picBox.Image);
        }
    }

    // creates image with solid background
    private Bitmap GetImage(int p, Size s)
    {
        var bmp = new Bitmap(s.Width, s.Height);
        using (Graphics gr = Graphics.FromImage(bmp))            
            gr.Clear(Color.FromArgb(_rnd.Next(255), _rnd.Next(255), _rnd.Next(255)));            
        return bmp;
    }
}