Keeping a PictureBox centered inside a container

前端 未结 3 743
闹比i
闹比i 2020-12-20 14:40

I am designing a simple picture viewer with ability to do some basic image processing. At the moment I have the problem of keeping the PictureBox centered insid

3条回答
  •  庸人自扰
    2020-12-20 15:30

    Givien a Form with TabControl, which has Dock set to Fill, below will keep your PictureBox in the centre. It also sets PictureBox size to Bitmap size:

        public partial class Form1 : Form
        {
            Bitmap b = new Bitmap(320, 200);
            public Form1()
            {
                InitializeComponent();
                CenterTheBox();
            }
    
            private void Form1_Resize(object sender, EventArgs e)
            {
                CenterTheBox();
            }
    
            void CenterTheBox()
            {
                pictureBox1.Size = b.Size;
                var left = (tabPage1.ClientRectangle.Width - pictureBox1.ClientRectangle.Width) / 2;
                var top = (tabPage1.ClientRectangle.Height - pictureBox1.ClientRectangle.Height) / 2;
                pictureBox1.Location = new Point(tabPage1.ClientRectangle.Location.X + left, tabPage1.ClientRectangle.Location.Y + top);
    
            }
        }
    

提交回复
热议问题