图像上的C#条形码太厚

时间:2014-04-05 14:43:44

标签: c# winforms pdf drawing barcode

我制作了一个Windows窗体应用程序,我希望生成带有条形码的送货单。我嵌入了条形码字体,但是我收到了错误。请参阅此问题:Embed Barcode in C# PDF Library

现在,我想从条形码制作图像并将此图像嵌入到我的送货单上。我在Google上搜索了这个,我找到了以下代码:

    private Image DrawBarcodeAfleverbonImage(String text)
    {
        Font barcodeFont = new Font("Bar-Code 39", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
        //Font barcodeFont = new Font("Arial", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);

        //first, create a dummy bitmap just to get a graphics object
        Image img = new Bitmap(1, 1);
        Graphics drawing = Graphics.FromImage(img);

        //measure the string to see how big the image needs to be
        SizeF textSize = drawing.MeasureString(text, barcodeFont);

        //free up the dummy image and old graphics object
        img.Dispose();
        drawing.Dispose();

        //create a new image of the right size
        img = new Bitmap((int)textSize.Width, (int)textSize.Height);

        drawing = Graphics.FromImage(img);

        //create a brush for the text
        Brush textBrush = new SolidBrush(Color.Black);
        drawing.DrawString(text, barcodeFont, textBrush, 0, 0);

        drawing.Save();
        img.Save(@"C:\Users\Marten\Documents\test.png");

        textBrush.Dispose();
        drawing.Dispose();

        return img;

如果我运行程序,将创建一个图像。只有一个问题:条形码字体太厚,所以我无法扫描:

enter image description here

有什么问题?

1 个答案:

答案 0 :(得分:1)

您需要在绘制文本之前设置背景颜色:

drawing.Clear(Color.White);
drawing.DrawString(text, barcodeFont, textBrush, 0, 0);

或者,如果您想要透明背景,则需要关闭字体平滑。

drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
drawing.DrawString(text, barcodeFont, textBrush, 0, 0);