TBarCode .NET 常见问题
如何控制位图的透明度
如何控制位图的透明度
以位图格式创建条码时,有两种方式可以调整背景:
- IsBackgroundTransparent = TRUE → 绘制条码时(DC、Graphics、Bitmap)只绘制条形,其余部分保持透空
- IsBackgroundTransparent = FALSE → 绘制条码时(DC、Graphics、Bitmap)先填充背景,然后再绘制条形
推荐的工作流程
如果您想创建一个背景透明的位图条码,需要单独设置透明色。具体做法是:先绘制到位图中,设置透明度,然后再保存。可以尝试以下两种方式之一:
方式一
以白色背景绘制条码:
- IsBackgroundTransparent := FALSE (→ 条码库会绘制白色背景)
指定透明色:
- bitmap.MakeTransparent( Color.White ); //make be background transparent - this will be an index (rather than an alpha) transparency
C# 示例代码:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = false;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = new Bitmap(width, height);
Graphics gfx = Graphics.FromImage(bitmap);
BC.Draw(gfx);
bitmap.MakeTransparent(Color.White);
bitmap.Save("c:\\temp\\test1a.png", System.Drawing.Imaging.ImageFormat.Png);
不使用 graphics 对象的变体写法:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = false;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = BC.DrawBitmap();
bitmap.MakeTransparent(Color.White);
bitmap.Save("c:\\temp\\test1b.png", System.Drawing.Imaging.ImageFormat.Png);
方式二
绘制不带背景的条码:
- IsBackgroundTransparent := FALSE (→ 条码库会绘制白色背景)
以透明方式填充背景:
- gfx.Clear(Color.Transparent);
C# 示例代码:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = true;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = new Bitmap(width, height);
Graphics gfx = Graphics.FromImage(bitmap);
gfx.Clear(Color.Transparent);
gfx.Flush();
BC.Draw(gfx);
bitmap.Save("c:\\temp\\test2.png", System.Drawing.Imaging.ImageFormat.Png);
说明
- 请注意,该示例条码并未针对像素进行优化。
- 建议使用 PNG 图像格式。
- 有关透明度的更多信息,请参阅此处。