我需要在C#中使用二维数组创建一个新的矩形。
我创建了一个名为brick_fw的图像,并将其导入到我正在创建的游戏的IDE中。
这是我的代码(在它自己的名为Brick的类中):
brickLength = 60;
brickHeight = 20;
int[,] brickLocation = { { 0, 0 }, { 62, 0 }, { 123, 0 }, { 184, 0 }, { 245, 0 }, { 306, 0 }, { 367, 0 } };
bool[] brickLive = { true, true, true, true, true, true, true };
brickImage = Breakout.Properties.Resources.brick_fw;
brickRec = new Rectangle(x, y, brickLength, brickHeight);
我在这里遇到的问题是;
brickRec
只能使用x和y的整数值,并且只接受这种表示新矩形的方式(这意味着如果我从括号中删除x和y并将其替换为brickLocation
,则编译器将呻吟)。
目前,编译器只会在程序中绘制一块砖,因为它没有考虑二维数组。
有没有办法在Rectangle函数中表示这个brickLocation
?
编辑:
public Brick()
{
brickLength = 60;
brickHeight = 20;
int[,] brickLocation = { { 0, 0 }, { 62, 0 }, { 123, 0 }, { 184, 0 }, { 245, 0 }, { 306, 0 }, { 367, 0 } };
bool[] brickLive = { true, true, true, true, true, true, true };
brickImage = Breakout.Properties.Resources.brick_fw;
for (int i = 0; i < brickLocation.GetLength(0); i++)
{
brickRec = new Rectangle(brickLocation[i, 0], brickLocation[i, 1], brickLength, brickHeight);
}
}
public void drawBrick(Graphics paper)
{
paper.DrawImage(brickImage, brickRec);
}
答案 0 :(得分:0)
Rectangle
值只能表示一个矩形,因此如果您想要多个矩形,则可以遍历数组的一个维度,并为每对值创建一个矩形:
for (int i = 0; i < brickLocation.GetLength(0); i++) {
brickRec = new Rectangle(brickLocation[i, 0], brickLocation[i, 1], brickLength, brickHeight);
// draw the rectangle
}
要绘制与矩形创建分开的矩形,您可以将它们放在矩形数组中:
private Rectangle[] brickRec;
public Brick()
{
brickLength = 60;
brickHeight = 20;
int[,] brickLocation = { { 0, 0 }, { 62, 0 }, { 123, 0 }, { 184, 0 }, { 245, 0 }, { 306, 0 }, { 367, 0 } };
bool[] brickLive = { true, true, true, true, true, true, true };
brickImage = Breakout.Properties.Resources.brick_fw;
brickRec = new Rectangle[brickLocation.GetLength(0)];
for (int i = 0; i < brickLocation.GetLength(0); i++)
{
brickRec[i] = new Rectangle(brickLocation[i, 0], brickLocation[i, 1], brickLength, brickHeight);
}
}
public void drawBrick(Graphics paper)
{
for (int i = 0; i < brickRec.Length; i++) {
paper.DrawImage(brickImage, brickRec[i]);
}
}