我正在设计一个能够进行基本图像处理的简单图片查看器。目前我遇到的问题是始终将PictureBox
置于TabPage
内,并保持图片框的宽度和大小与其显示的图片相同。到目前为止,我没有成功。
我有以下代码,我在表单构造函数中调用它以将其放在中心位置。它第一次使图片框居中:
private void SetPictureBoxOriginalSizeAndLocation(bool makeImageNull = false, DockStyle dockStyle = DockStyle.None)
{
if (makeImageNull) picBoxView.Image = null;
picBoxView.Dock = dockStyle;
var xPoint = tabImageView.Location.X + ((splitContainer.Panel2.Width / 2) / 2);
var yPoint = tabImageView.Location.Y;
var width = tabImageView.Width / 2;
var height = (tabImageView.Height / 2) - toolStripImageView.Height;
if (picBoxView.Image == null) return;
//Resize image according to width
picBoxView.Image = ImageMethods.ResizeImage(picBoxView.Image.Tag.ToString(), width, height, false);
picBoxView.Location = new Point(xPoint, yPoint);
picBoxView.Width = width;
picBoxView.Height = height;
}
但它不会将图片框调整为其图像(您可以看到图片框控件的背面颜色为黑色部分):
一旦我调整表单大小,问题就会越来越严重,图片框的位置会越来越高:
我在表单的resize事件中调用上面的代码,不知道为什么它在应用程序启动时有效。如果有人能告诉我应该照顾哪些属性以获得一个总是和它的图像一样大的中心图片框,那将会很好。
答案 0 :(得分:17)
如果只将Anchor
样式设置为无:
picBoxView = new PictureBox();
picBoxView.SizeMode = PictureBoxSizeMode.AutoSize;
picBoxView.Anchor = AnchorStyles.None;
tabImageView.Controls.Add(picBoxView);
CenterPictureBox(picBoxView, myImage);
每当您更改PictureBox
的图片时,最初只需居中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();
}
当父容器调整大小时,让Anchor = None
为PictureBox
控件将为您设置中心,因为它“未”锚定到默认的Left和Top位置。
答案 1 :(得分:1)
如果Form
的{{1}} TabControl
设置为Dock
,则Fill
会将PictureBox
保留在中心位置。它还将PictureBox
尺寸设置为Bitmap
尺寸:
public partial class Form1 : Form
{
Bitmap b = new Bitmap(320, 200);
public Form1()
{
InitializeComponent();
CenterTheBox();
}
private void Form1_Resize(object sender, EventArgs e)
{
CenterTheBox();
}
void CenterTheBox()
{
pictureBox1.Size = b.Size;
var left = (tabPage1.ClientRectangle.Width - pictureBox1.ClientRectangle.Width) / 2;
var top = (tabPage1.ClientRectangle.Height - pictureBox1.ClientRectangle.Height) / 2;
pictureBox1.Location = new Point(tabPage1.ClientRectangle.Location.X + left, tabPage1.ClientRectangle.Location.Y + top);
}
}
答案 2 :(得分:1)
我相信你的问题就在这里
var xPoint = tabImageView.Location.X + ((splitContainer.Panel2.Width / 2) / 2);
var yPoint = tabImageView.Location.Y;
var width = tabImageView.Width / 2;
var height = (tabImageView.Height / 2) - toolStripImageView.Height;
ypoint被设置为tabImageView Y,但是应该将其设置为
tabImageView.Location.Y + (tabImageView.Size.Height - picBoxView.Size.Height)/2
与xPoint几乎相同
tabImageView.Location.X + (tabImageView.Size.Width - picBoxView.Size.Width)/2
和
width = picBoxView.Image.Width;
height = picBoxView.Image.Height;