Centered and scrolled PictureBox in WinForms

前端 未结 3 1521
孤街浪徒
孤街浪徒 2021-01-13 20:16

I\'m developing a WinForms application and can\'t figure out how to resolve an issue. I need to show an image in a Form. Because the image can be arbitrarily large, I need s

相关标签:
3条回答
  • 2021-01-13 20:47

    The picturebox has to be set to autosize. anchored at the center (or a border).

    You could manage all of this in the designer, don't undertand your problem with that.

    The panel has to be set to autoscroll to true.

    0 讨论(0)
  • 2021-01-13 20:57

    For the PictureBox, set SizeMode = AutoSize, Anchor it Top, Left, and set its Location to 0, 0.

    Set Panel.AutSize to False and Panel.AutoScroll to True.

    When you set the PictureBox.Image property, it will auto-size to the size of the image. You can then use that size to set the panel's AutoScrollPosition property:

    public Image CapturedImage
    {
        set 
        { 
            pictureBoxCapturedImage.Image = value;
            panelCapturedImage.AutoScrollPosition = 
                new Point { 
                    X = (pictureBoxCapturedImage.Width - panelCapturedImage.Width) / 2, 
                    Y = (pictureBoxCapturedImage.Height - panelCapturedImage.Height) / 2 
                };
        }
    }
    

    If the image is smaller then then panel's size, it will remain in the upper left corner. If you want it centered within the panel, you'll have to add logic to set its Location appropriately.

    0 讨论(0)
  • 2021-01-13 21:08

    Based on earlier answers I was able to create this full example:

    private void testShowPictureBox()
        {
            /* format form */
            Form frmShowPic = new Form();
            frmShowPic.Width = 234;
            frmShowPic.Height = 332;
            frmShowPic.MinimizeBox = false;
            frmShowPic.MaximizeBox = false;
            frmShowPic.ShowIcon = false;
            frmShowPic.StartPosition = FormStartPosition.CenterScreen;
    
            frmShowPic.Text = "Show Picture";
    
            /* add panel */
            Panel panPic = new Panel();
            panPic.AutoSize = false;
            panPic.AutoScroll = true;
            panPic.Dock = DockStyle.Fill;
    
            /* add picture box */
            PictureBox pbPic = new PictureBox();
            pbPic.SizeMode = PictureBoxSizeMode.AutoSize;
            pbPic.Location = new Point(0, 0);
    
            panPic.Controls.Add(pbPic);
            frmShowPic.Controls.Add(panPic);
    
            /* define image */
            pbPic.ImageLocation = @"c:\temp\pic.png";
    
            frmShowPic.ShowDialog();
       }
    
    0 讨论(0)
提交回复
热议问题