我正在开发 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);
这是我设置图像的地方:
public Image CapturedImage
{
set
{
pictureBoxCapturedImage.Image = value;
pictureBoxCapturedImage.Size = value.Size;
}
}
For the PictureBox
, set SizeMode = AutoSize
, Anchor
it Top, Left
,并设置其Location
to 0, 0
.
Set Panel.AutSize
to False
and Panel.AutoScroll
to True
.
当您设置PictureBox.Image
属性,它会自动调整图像的大小。然后您可以使用该大小来设置面板的自动滚动位置财产:
public Image CapturedImage
{
set
{
pictureBoxCapturedImage.Image = value;
panelCapturedImage.AutoScrollPosition =
new Point {
X = (pictureBoxCapturedImage.Width - panelCapturedImage.Width) / 2,
Y = (pictureBoxCapturedImage.Height - panelCapturedImage.Height) / 2
};
}
}
如果图像小于面板的尺寸,它将保留在左上角。如果您希望它在面板中居中,则必须添加逻辑来设置其Location
适当地。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)