最终目标是一个有点可玩的记忆游戏。目前,我陷入了渲染问题。我有以下课程:
Field,它是抽象的UserControl
:
public abstract class Field : UserControl
{
protected PictureBox _pictureBox;
public Field()
{
_pictureBox = new PictureBox();
_pictureBox.Image = Properties.Resources.empty;
_pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
_pictureBox.BorderStyle = BorderStyle.FixedSingle;
this.Controls.Add(_pictureBox);
}
// ...
// some abstract methods, not currently important
}
MemoryField,从字段派生:
public class MemoryField : Field
{
public MemoryField(Form parent, int xPos, int yPos, int xSize, int ySize)
{
_pictureBox.ClientSize = new Size(xSize, ySize);
_pictureBox.Location = new Point(xPos, yPos);
_pictureBox.Parent = parent;
}
// ...
}
最后是MainForm,这是我的应用程序的入口点:
public partial class MainForm : Form
{
private readonly int fieldWidth = 100; // 150 no rendering problems at all
private readonly int fieldHeight = 100;
public MainForm() { InitializeComponent(); }
private void MainForm_Load(object sender, EventArgs e)
{
for (int y = 0; y < 6; y++) // 6 rows
{
for (int x = 0; x < 10; x++) // 10 columns
{
Field field = new MemoryField(this,
x * (fieldWidth + 3), // xPos, 3 is for a small space between fields
labelTimer.Location.Y + labelTimer.Height + y * (fieldHeight + 3), // yPos
fieldWidth,
fieldHeight);
this.Controls.Add(field);
}
}
}
}
这是我的问题所在:在那些for
循环中,我试图生成一个6x10的Field
s网格(每个网格包含PictureBox
100x100 px大小)。我几乎成功完成了此操作,因为第二个字段未正确显示:
[我发现唯一可行的方法(完全解决了问题)使字段变大(即150px)。另一方面,将其缩小(即50px)会使问题更大:
也许是有用的信息和我尝试过的事情:
AutoSize = true;
和AutoSizeMode = GrowAndShrink;
menuStrip
和label
除外PictureBox.Image
属性,而该[[没有起作用。PictureBox
控件(而不使用Field
作为PictureBox
包装器)创建网格,而labelTimer
放置在该[问题区域]中,该问题区域[[确实会根据我的确切放置位置来解决问题。 (因为字段的位置取决于labelTimer
的位置和高度)public abstract class Field : PictureBox {
public Field() {
Image = Image.FromFile(@"Bomb01.jpg");
SizeMode = PictureBoxSizeMode.StretchImage;
BorderStyle = BorderStyle.FixedSingle;
Size = new Size(100, 100);
}
// ...
// some abstract methods, not currently important
}
public class MemoryField : Field {
public MemoryField(Form parent, int xPos, int yPos, int xSize, int ySize) {
ClientSize = new Size(xSize, ySize);
Location = new Point(xPos, yPos);
}
// ...
}
它无法正常工作的真正原因与每个Field
及其子组件的
大小和位置都有关。您不应相对于其父级
您还应该将Location
设置每个_pictureBox
的MemoryField
,而应相对于其父级Location
更改MemoryField
的Form
。MemoryField
的大小设置为其子_pictureBox
的大小,否则将无法正确调整其大小以适应其内容。public class MemoryField : Field { public MemoryField(Form parent, int xSize, int ySize) { _pictureBox.ClientSize = new Size(xSize, ySize); // I removed the setting of Location for the _pictureBox. this.Size = _pictureBox.ClientSize; // size container to its wrapped PictureBox this.Parent = parent; // not needed } // ... }
并将您的创建内循环更改为
for (int x = 0; x < 10; x++) // 10 columns
{
Field field = new MemoryField(this,
fieldWidth,
fieldHeight);
field.Location = new Point(x * (fieldWidth + 3), 0 + 0 + y * (fieldHeight + 3)); // Set the Location here instead!
this.Controls.Add(field);
}