c# 如何让picturebox控件 居中显示在panel中

2024-12-18 10:36:55
推荐回答(3个)
回答1:

示例:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace ToolTipTest
{
///


/// Form1 的摘要说明。
///

public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private System.ComponentModel.IContainer components;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

///
/// 清理所有正在使用的资源。
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///

private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panel1
//
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(736, 273);
this.panel1.TabIndex = 0;
this.panel1.SizeChanged += new System.EventHandler(this.panel1_SizeChanged);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(736, 273);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///
/// 应用程序的主入口点。
///

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private PictureBox[] p =new PictureBox[100];
private void Form1_Load(object sender, System.EventArgs e)
{

for(int i=0;i{
p[i]=new PictureBox();
p[i].BorderStyle=BorderStyle.FixedSingle;
this.panel1.Controls.Add(p[i]);
}

SetControlsLocation();

}

private void panel1_SizeChanged(object sender, System.EventArgs e)
{
SetControlsLocation();
}
private void SetControlsLocation()
{
this.panel1.Hide();
int ControlWidth =this.panel1.Width/10;
int ControlHeight =this.panel1.Height/10;
int x =0;
int y=0;
foreach (Control tmpCtr in this.panel1.Controls)
{
tmpCtr.Width =ControlWidth;
tmpCtr.Height =ControlHeight;
if(this.panel1.Width-x{
x=0;
y+=ControlHeight;
}
tmpCtr.Left =x;
tmpCtr.Top=y;
tmpCtr.BringToFront();
x+=ControlWidth;

}
this.panel1.Show();
}

}
}

回答2:

完全填充this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
固定的话只有计算位置了
pictureBox1.Location = new System.Drawing.Point((pictureBox1.Parent.Size.Width - pictureBox1.Size.Width) / 2, (pictureBox1.Parent.Size.Height - pictureBox1.Size.Height) / 2);
非固定可能是这个

回答3:

位置你可以自己算出来,大概是

picturebox.Top=(panel.Height-picturebox.Height)/2;
pictureboxT.Left=(panel.Width-picturebox.Width)/2;