在WinForms中居中滚动的PictureBox

bra*_*les 4 .net c# scrollbar picturebox winforms

我正在开发WinForms应用程序,无法解决问题。我需要在表单中显示图像。因为图像可以任意大,所以我需要在包含图像的图片框上滚动条,以便用户可以完全看到它。我四处搜寻,发现实现此目的的最佳方法是将PictureBox添加为面板的子控件,并使面板可自动调整大小和可自动滚动。我以编程方式进行了此操作,因为使用设计器后,我无法将图片框作为面板的子控件插入。我现在面临的问题是我似乎无法居中和滚动图片框同时显示。如果将图片框的锚点放在上,左,下,右,则不会显示滚动条,并且显示的图像很奇怪,如果将锚点放回到左上角,则图像不会居中。

有什么办法可以同时做这两者?这是我的面板和图片框的代码:

this.panelCapturedImage = new System.Windows.Forms.Panel();
this.panelCapturedImage.SuspendLayout();
this.panelCapturedImage.AutoScroll = true;
this.panelCapturedImage.AutoSize = true;
this.panelCapturedImage.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panelCapturedImage.Controls.Add(this.pictureBoxCapturedImage);
this.panelCapturedImage.Location = new System.Drawing.Point(0, 49);
this.panelCapturedImage.Name = "panelCapturedImage";
this.panelCapturedImage.Size = new System.Drawing.Size(3, 3);
this.panelCapturedImage.TabIndex = 4;

this.pictureBoxCapturedImage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBoxCapturedImage.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCapturedImage.Name = "pictureBoxCapturedImage";
this.pictureBoxCapturedImage.Size = new System.Drawing.Size(0, 0);
this.pictureBoxCapturedImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBoxCapturedImage.TabIndex = 0;
this.pictureBoxCapturedImage.TabStop = false;

this.panelCapturedImage.Controls.Add(this.pictureBoxCapturedImage);
Run Code Online (Sandbox Code Playgroud)

这是我设置图像的位置:

public Image CapturedImage
{
    set 
    { 
        pictureBoxCapturedImage.Image = value;
        pictureBoxCapturedImage.Size = value.Size;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*ata 5

对于PictureBox,集合SizeMode = AutoSizeAnchorTop, Left,并设置其Location0, 0

设置Panel.AutSizeFalsePanel.AutoScrollTrue

设置PictureBox.Image属性后,它将自动调整为图像大小。然后,您可以使用该大小来设置面板的AutoScrollPosition属性:

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

如果图像小于面板尺寸,则图像将保留在左上角。如果要将其居中放置在面板中,则必须添加逻辑以对其进行Location适当设置。