Is it possible to stretch picture in PictureBox wi

2019-09-20 02:48发布

I have a PictureBox inside the Panel with picture box Dock = DockStyle.Fill.

When I assign picture into the PictureBox, picture is stretch horizontal to fit the space available and need a vertical scrollbar to scroll the image. I do not need of horizontal scrollbar in it.

Please do not make this question as duplicate.. I have clearly mentioned that I only need of vertical scrollbar with run time resizing option of the panel.

Note: Panel size may change at run time (so, obviously PictureBox size too).

Please help me out.

1条回答
迷人小祖宗
2楼-- · 2019-09-20 03:09

This solution uses a simple resize method which you can call whenever it should update its size.

prerequisites:

  • Turn off the docking for the PictureBox

  • Set the AutoScroll property of the Panel to true

Resizing method:

private void panel1_Resize(object sender, EventArgs e)
{
    ResizePb();
}

private void ResizePb()
{
    //Make the pciturebox as wide as the panel, keep in mind the scrollbars
    pictureBox1.Width = panel1.Width - SystemInformation.VerticalScrollBarWidth - 5; 
    //Calculate the aspect ratio of the image based on its new width
    var aspect = (double)panel1.Width / pictureBox1.Image.Width;
    //Set height according to aspect ratio
    var height = Convert.ToInt32(aspect * pictureBox1.Image.Height);
    pictureBox1.Height = height;
}
查看更多
登录 后发表回答