我试图用C#画一个8x8的棋盘。这是我第一次尝试绘制它。它不会吸引董事会,我也找不到我失踪的东西。
public void Form1_Load(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(8 * 100, 8 * 100);
Graphics g = Graphics.FromImage(bm);
Color color1, color2;
for (int i = 0; i < 8; i++)
{
if (i % 2 == 0)
{
color1 = Color.Black;
color2 = Color.White;
}
else
{
color1 = Color.White;
color2 = Color.Black;
}
SolidBrush blackBrush = new SolidBrush(color1);
SolidBrush whiteBrush = new SolidBrush(color2);
for (int j = 0; j < 8; j++)
{
if (j % 2 == 0)
g.FillRectangle(blackBrush, i * 100, j * 100, 100, 100);
else
g.FillRectangle(whiteBrush, i * 100, j * 100, 100, 100);
}
}
g.DrawImage(bm, 150, 200);
}
答案 0 :(得分:3)
将BackgroundImage = bm;
添加到代码的底部。
您正在绘制电路板,只是不显示位图......
编辑:我不确定你是否感兴趣,但我重写了这段代码。
Bitmap bm = new Bitmap(800, 800);
using (Graphics g = Graphics.FromImage(bm))
using (SolidBrush blackBrush = new SolidBrush(Color.Black))
using (SolidBrush whiteBrush = new SolidBrush(Color.White))
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if ((j % 2 == 0 && i % 2 == 0) || (j % 2 != 0 && i % 2 != 0))
g.FillRectangle(blackBrush, i * 100, j * 100, 100, 100);
else if ((j % 2 == 0 && i % 2 != 0) || (j % 2 != 0 && i % 2 == 0))
g.FillRectangle(whiteBrush, i * 100, j * 100, 100, 100);
}
}
BackgroundImage = bm;
}
如果您想制作国际象棋游戏,这个项目也可以提供帮助:http://www.codeproject.com/Articles/20736/C-C-CLI-Micro-Chess-Huo-Chess
答案 1 :(得分:0)
//Variables
int rowSize = 8;
int colSize = 8;
//Calculation
for (int row = 0; row < rowSize; row++) //Loop throw ROW's
{
for (int col = 0; col < colSize; col++) //Loop throw COL's
{
if ((row + col) % 2 == 0) //Check if cells is EVEN
{
Console.Write("X"); //White square
}
else
{
Console.Write("O"); //Black square
}
}
Console.WriteLine(); //Switch to a new line
考虑将棋盘分解成行和列(水平和垂直)。通过for循环对第0至8行进行索引。列相同。对于每个正方形,请检查该行与该列的索引总和是否为“ par”(除以2的其余部分为0),则等于白色正方形。否则,它将分配一个黑色正方形。诀窍是((row + col)%2)。交替给出0或1的值。在“ for循环”列的每次迭代结束时,该行都会更改。
答案 2 :(得分:0)
出于性能方面的考虑,您也可以跳过绘制其他彩色图块,而仅先用辅助色填充背景,然后迭代主要色图块。示例:
public static class GridGenerator
{
public static void CreateGridBackground()
{
DrawingVisual visual = new DrawingVisual();
DrawingContext context = visual.RenderOpen();
context.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 256, 512));
for (int xRow = 0; xRow < 256 / 16; xRow++)
{
for (int yColumn = 0; yColumn < 512 / 16; yColumn++)
{
if ((yColumn % 2 == 0 && xRow % 2 == 0) || (yColumn % 2 != 0 && xRow % 2 != 0))
{
context.DrawRectangle(Brushes.White, null, new Rect(xRow * 16, yColumn * 16, 16, 16));
}
}
}
context.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap(256, 512, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(new FileStream("C:/Users/Krythic/Desktop/Test.png", FileMode.Create));
}
}
理论上这要快50%(实际上没有进行基准测试,因此请随意将其视为虚数),因为您是通过填充一种颜色将图形切成两半,而不是将其实际绘制为单个图块。只是说接受或离开它。