代码之家  ›  专栏  ›  技术社区  ›  user2257918

为什么此代码不创建棋盘格图案?

  •  0
  • user2257918  · 技术社区  · 6 年前

    我想知道为什么这段代码不会生成棋盘模式?

    pbImage.Image = new Bitmap(8, 8);
            Bitmap bmp = ((Bitmap)pbImage.Image);
            byte[] bArr = new byte[64];
            int currentX = 0;
            int currentY = 0;
            Color color = Color.Black;
            do
            {
                currentY = 0;
                do
                {
                    bmp.SetPixel(currentX, currentY, color);
                    if (color == Color.Black) color = Color.White; else color = Color.Black;
                    currentY++;
                } while (currentY < bitmapHeight);
                currentX++;
            } while (currentX < bitmapWidth);
    
            pbImage.Refresh();
    

    编辑:我意识到我需要用
    new Bitmap(bitmapWidth, bitmapHeight, PixelFormat.Format8bppIndexed) 而且SetPixel似乎不支持索引图像,需要颜色。

    我的观点是,我想创建原始(纯字节数组)灰度图像,并将其显示在图片框中,同时尽可能保持简单,而不使用任何外部库。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Nyerguds    6 年前

    计算失败,因为如果在每个像素处切换,则即使以颜色0开头的行也将以颜色1结尾,这意味着下一行将再次以颜色0开头。

    0101010101010101
    0101010101010101
    0101010101010101
    0101010101010101
    etc...

    但是,由于在X和Y坐标系中,图案上1个像素的任何水平和垂直移动都会改变颜色,因此可以将填充或非填充像素的实际计算简化为 (x + y) % 2 == 0

    我在下面介绍的棋盘生成函数将一组颜色作为调色板,并允许您指定调色板中的哪些特定索引用作图案上使用的两种颜色。如果您只想要一幅只有黑白两色调色板的图像,您可以这样称呼它:

    Bitmap check = GenerateCheckerboardImage(8, 8, new Color[]{Color.Black, Color.White}, 0,1);
    

    生成函数:

    public static Bitmap GenerateCheckerboardImage(Int32 width, Int32 height, Color[] colors, Byte color1, Byte color2)
    {
        Byte[] patternArray = new Byte[width * height];
        for (Int32 y = 0; y < height; y++)
        {
            for (Int32 x = 0; x < width; x++)
            {
                Int32 offset = x + y * height;
                patternArray[offset] = (((x + y) % 2 == 0) ? color1 : color2);
            }
        }
        return BuildImage(patternArray, width, height, width, PixelFormat.Format8bppIndexed, colors, Color.Black);
    }
    

    这个 BuildImage 我使用的函数是一个通用函数,用于将字节数组转换为图像。你可以找到它 in this answer

    正如在该问题的其余部分及其答案中所解释的 stride 参数是图像数据每行上的字节数。对于我们在这里得到的构造的8位数组,这与宽度完全相同,但当 正在加载 它通常四舍五入为4的倍数,并且可以包含未使用的填充字节。(该函数负责所有这些,因此输入字节数组没有此类要求。)