我正在尝试使用 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);
     }

最佳答案

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

关于C#画棋盘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18203809/

10-11 11:04