1

这是我创建条形码图像的代码:

 class Program
    {
        static void Main(string[] args)
        {
            CreateBarcode("The quick brown fox jumps over the lazy dog".ToUpper());

        }

        private static void CreateBarcode(string code)
        {
            var myBitmap = new Bitmap(500, 50);
            var g = Graphics.FromImage(myBitmap);
            var jgpEncoder = GetEncoder(ImageFormat.Jpeg);

            g.Clear(Color.White);

            var strFormat = new StringFormat { Alignment = StringAlignment.Center };
            g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);

            var myEncoder = Encoder.Quality;
            var myEncoderParameters = new EncoderParameters(1);

            var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            //MemoryStream memoryStrem = new 
            myBitmap.Save(@"d:\Barcode.jpg", jgpEncoder, myEncoderParameters);
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();

            foreach (var codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        } 

    }

但是,这行得通,这一行:g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);

如您所见,这里的宽度是 500。现在,如果我指定一大段文字,我担心 500 是不够的。有没有办法根据内容使这个宽度动态化?

4

1 回答 1

0

它太旧了,无法回答,仍然在发帖,因为它可能对某人有所帮助。我们可以使用虚拟位图创建图形对象并尝试查找字体长度,然后重新初始化位图和图形对象。

var myBitmap = new Bitmap(1, 1);
Font threeOfNine = new Font("Free 3 of 9", 60, FontStyle.Regular, GraphicsUnit.Point);
var g = Graphics.FromImage(myBitmap);
SizeF dataSize = g.MeasureString(code, threeOfNine);
myBitmap = new Bitmap(myBitmap, dataSize.ToSize());
g = Graphics.FromImage(myBitmap);
于 2016-07-24T17:48:57.323 回答