FAQ TBarCode .NET
Come posso creare una bitmap con un'altezza barre specifica?
Come posso creare una bitmap con un'altezza barre specifica?
Il seguente codice di esempio mostra come creare una bitmap con una particolare altezza barre per EAN 13 (può essere modificato per altri tipi di codici a barre lineari).
double dpi = 300;
double barHeightinMM = 23;
double symbolHeightinMM = 26;
double nominalNarrowBarWidthinMM = 0.33;
Graphics gfx = this.CreateGraphics(); // graphics of any screen DC
Barcode ean13 = new Barcode();
ean13.BarcodeType = BarcodeType.Ean13;
ean13.Data = "123456789012";
ean13.Dpi = dpi;
// 1 Pixel in mm
double PxtoMm = 25.4 / dpi;
// how many Pixels are 0.33 mm => We have to round depending on DPI
int narrowBarinPx = (int) Math.Round (nominalNarrowBarWidthinMM / PxtoMm);
double narrowBarinMM = narrowBarinPx * PxtoMm;
System.Diagnostics.Debug.WriteLine("Narrow bar width in mm (rounded to full Pixels): " + narrowBarinMM);
// calculate width in pixels by using the number of "modules" in the barcode
int symbolWidthinPixels = ean13.CalculateNumberOfModules() * narrowBarinPx;
// set font size to an automatic size based upon module width
double fontSizePt = 10 * Math.Round(narrowBarinMM, 3) / 0.339;
ean13.Font = new Font("Consolas", (float) fontSizePt);
// Case A: desired bar height is 23 mm
{
int barHeightinPx = (int) Math.Round(barHeightinMM / PxtoMm, 0);
System.Diagnostics.Debug.WriteLine("Bar height in Pixels : " + barHeightinPx);
// calculate actual text area height
float textAreaHeightMM = ean13.CalculateTextAreaHeight(null);
int textAreaHeightPx = (int) (0.5 + textAreaHeightMM / PxtoMm);
System.Diagnostics.Debug.WriteLine("Text height in Pixels: " + textAreaHeightPx);
int symbolHeightinPx = barHeightinPx + textAreaHeightPx;
// set bounding rectangle in Pixels
ean13.BoundingRectangle = new Rectangle(0,0, symbolWidthinPixels, symbolHeightinPx);
// Draw directly to bitmap file
ean13.Draw(AppDomain.CurrentDomain.BaseDirectory + @"\EAN13-caseA.BMP", ImageType.Bmp, gfx, 1);
// Draw to Picture Box
// Option A
// scale font depending on DPI ratio (required if internal DC is used)
ean13.FontHeight = (int) (fontSizePt * dpi / gfx.DpiY);
pictureBoxEAN13.Image = ean13.DrawBitmap();
// Option B
// ignore DC resolution + use Pt font size
ean13.IgnoreDpiFromDC = true;
ean13.FontHeight = (int) fontSizePt;
pictureBoxEAN13.Image = ean13.DrawBitmap();
}
// Case B: desired symbol height (incl. text) is 26 mm
{
int symbolHeightinPx = (int) Math.Round (symbolHeightinMM / PxtoMm, 0);
System.Diagnostics.Debug.WriteLine("Symbol height in Pixels : " + symbolHeightinPx);
// set bounding rectangle in Pixels
ean13.BoundingRectangle = new Rectangle(0, 0, symbolWidthinPixels, symbolHeightinPx);
// Draw directly to bitmap file
ean13.Draw(AppDomain.CurrentDomain.BaseDirectory + @"\EAN13-caseB.BMP", ImageType.Bmp, gfx, 1);
}