Keeping a PictureBox centered inside a container

前端 未结 3 753
闹比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:32

    It's pretty easy if you just set the Anchor style to none:

    picBoxView = new PictureBox();
    picBoxView.SizeMode = PictureBoxSizeMode.AutoSize;
    picBoxView.Anchor = AnchorStyles.None;
    tabImageView.Controls.Add(picBoxView);
    CenterPictureBox(picBoxView, myImage);
    

    Then just center the PictureBox initially whenever you change the image of the PictureBox:

    private void CenterPictureBox(PictureBox picBox, Bitmap picImage) {
      picBox.Image = picImage;
      picBox.Location = new Point((picBox.Parent.ClientSize.Width / 2) - (picImage.Width / 2),
                                  (picBox.Parent.ClientSize.Height / 2) - (picImage.Height / 2));
      picBox.Refresh();
    }
    

    Having the Anchor = None will center the PictureBox control for you whenever the parent container gets resized because it "isn't" anchored to the default Left and Top locations.

提交回复
热议问题