Skip to content

Using a custom renderer

Michael Jahn edited this page Jun 12, 2018 · 1 revision

The class ZXing.BarcodeWriter generates a barcode image object which uses a platform specific output format. For example the barcode writer for the full .Net framework generates a Bitmap instance, for Unity it is a Color32 array, for UWP it is a Windows.Graphics.Imaging.SoftwareBitmap and so on.

If you want to modify the generated image but the output format should stay the same you simply have to write a new renderer class for use with the ZXing.BarcodeReader:

// the own custom renderer class
public class CustomBitmapRenderer : BitmapRenderer
{
   public override Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
   {
... your own custom implementation should be added here ...
   }
}

...
// usage example for the own custom renderer implementation
var writer = new BarcodeWriter
{
   Format = BarcodeFormat.QR_CODE,
   Renderer = new CustomBitmapRenderer()
};
var bitmapImage = writer.Write("<your content here>");
...

The WindowsFormsDemo shows a full sample implementation of the CustomBitmapRenderer.

Sometimes you want to support a different output format. In that case the class ZXing.BarcodeWriter<TOutput> can be used to build a barcode writer which uses a renderer class with a custom output format. First you have to create your own renderer class. The following code snippet demonstrate it with the existing renderer for SVG images.

public class SvgRenderer : IBarcodeRenderer<SvgRenderer.SvgImage>
{
   public SvgImage Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
   {
      var result = new SvgImage(matrix.Width, matrix.Height);

... create the svg paths here ...

      return result;
   }
}

Now you should create a custom barcode writer class which can be directly used in your projects.

public class BarcodeWriterSvg : BarcodeWriter<SvgRenderer.SvgImage>
{
   public BarcodeWriterSvg()
   {
      Renderer = new SvgRenderer();
   }
}

Use the barcode writer class in your code.

var writer = new BarcodeWriterSvg
{
   Format = BarcodeFormat.QR_CODE
};
var svgImage = writer.Write("<your content here>");