2

我正在使用 ZXing.NET 使用此代码生成条形码

BarcodeWriter barcodeWriter = new BarcodeWriter
{
    Format = BarcodeFormat,
    Options = new EncodingOptions
    {
        Width = barCodeWidth,
        Height = barCodeHeight,
        PureBarcode = !GenerateBarCodeWithText
    }
};

Bitmap barCodeBitmap = barcodeWriter.Write(content);

所以目前每个条形码(和文本)都是黑色的。例如,有没有办法可以传入一个Color对象来将条形码和文本着色为红色?我尝试了这个 hacky 解决方案来获取当前像素颜色,检查它是否为白色,如果不是,将其着色为指定的字体颜色。

for (int x = 0; x < barCodeBitmap.Width; x++)
{
    for (int y = 0; y < barCodeBitmap.Height; y++)
    {
        Color currentColor = barCodeBitmap.GetPixel(x, y);
        bool isWhite = currentColor == Color.White;

        if (!isWhite) // this pixel should get a new color
        {
            barCodeBitmap.SetPixel(x, y, fontColor); // set a new color
        }
    }
}

不幸的是,每个像素都被着色了..

4

1 回答 1

2

要为整个代码(包括文本)着色,您可以使用以下代码段:

BarcodeWriter barcodeWriter = new BarcodeWriter
{
   Format = BarcodeFormat,
   Options = new EncodingOptions
   {
      Width = barCodeWidth,
      Height = barCodeHeight,
      PureBarcode = !GenerateBarCodeWithText
   },
   Renderer = new BitmapRenderer
   {
      Foreground = Color.Red
   }
};

Bitmap barCodeBitmap = barcodeWriter.Write(content);

如果您想要条形码和文本的不同颜色,您必须编写自己的渲染器实现并使用它而不是 BitmapRenderer。您可以查看 BitmapRenderer 的源代码并将其用作您自己实现的模板:

https://github.com/micjahn/ZXing.Net/blob/master/Source/lib/renderer/BitmapRenderer.cs

例如添加一个新属性“TextColor”并在该行中使用它

var brush = new SolidBrush(Foreground);

变成

var brush = new SolidBrush(TextColor);
于 2019-11-28T07:02:34.843 回答