gpt4 book ai didi

c# - 在 WinForms 中居中和滚动的 PictureBox

转载 作者:太空狗 更新时间:2023-10-30 00:56:25 24 4
gpt4 key购买 nike

我正在开发 WinForms 应用程序,但不知道如何解决问题。我需要在表格中显示图像。因为图像可以任意大,所以我需要在包含图像的图片框上使用滚动条,以便用户可以完整地看到它。谷歌搜索我发现实现此目的的最佳方法是将 PictureBox 添加为面板的子控件,并使面板可自动调整大小和自动滚动。我以编程方式执行此操作,因为使用设计器我无法将图片框作为面板的子控件插入。我现在面临的问题是我似乎无法同时居中和滚动 图片框。如果我将图片框的 anchor 放在顶部、左侧、底部、右侧,则不会显示滚动条并且显示的图像很奇怪,如果我将 anchor 放回到左上角,则图像不会居中。

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

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;
}
}

最佳答案

对于PictureBox,设置SizeMode = AutoSizeAnchorTop, Left,并设置它的Location0, 0

Panel.AutSize 设置为 False 并将 Panel.AutoScroll 设置为 True

当您设置 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
};
}
}

如果图像小于面板的尺寸,它将保留在左上角。如果您希望它在面板中居中,则必须添加逻辑以适本地设置它的 Location

关于c# - 在 WinForms 中居中和滚动的 PictureBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7798509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com