DavBfr / dart_barcode

Barcode generation library
https://pub.dev/packages/barcode
Apache License 2.0
132 stars 41 forks source link

Determine number of elements/dots in a DataMatrix? #50

Closed jakobleck closed 1 year ago

jakobleck commented 1 year ago

Is there a way to determine the width/height of a generated DataMatrix barcode in number of "dots"/"squares"? The aim being to create a padding/"quiet zone" around the DataMatrix of width x*(dot width).

Having looked at the code it seems like this is only in the internal workings of the package, the private class _CodeSize or the rendering in makeBytes in Barcode2D, and currently not publicly accessible, right?

DavBfr commented 1 year ago

It's not accessible as is, but you can run the drawing method and count the squares returned.

jakobleck commented 1 year ago

Thanks for the hint, David. Feels like a workaround since the make() is called twice now, but it works. Counting the squares returned does not work directly because adjoining elements of the same color can be combined to one BarcodeElement. For example, a 10x10 DataMatrix can return 57 BarcodeElements from the make() function. I ended up using the minimum size of the BarcodeElements:

    ...
    int marginElements = 2;
    Barcode barcode = Barcode.dataMatrix();
    Iterable<BarcodeElement> barcodeElements = barcode.make(
      data,
      width: size,
      height: size,
    );
    double elementSize = barcodeElements.map((e) => e.width).reduce(math.min);
    double elementsPerSide = size / elementSize;
    double newElementSize = size / (elementsPerSide + 2 * marginElements);
    double marginSize = marginElements * newElementSize;
    double matrixSize = size - 2 * marginSize;
    String svgString = barcode.toSvg(
      data,
      width: matrixSize,
      height: matrixSize,
      color: color.value,
    );
    ...