Search code examples
c#xamarinxamarin.iosxamarin.formszxing

ZXing Barcode ImageView not showing generated barcode Xamarin Forms


I'm currently working on an crossplatform app using Xamarin Forms (shared). I need to generate a EAN-13 barcode, and my code works fine on Android, but nothing happens on iOS. I'm using ZXingBarcodeImageView. This is my code.

public class CardPage : ContentPage
{
  ZXingBarcodeImageView barcode = new ZXingBarcodeImageView
  {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
  };

  barcode.BarcodeFormat = ZXing.BarcodeFormat.EAN_13;
  barcode.BarcodeOptions.Height = 25;
  barcode.BarcodeOptions.Width = 75;
  barcode.BarcodeValue = "2800100028014";

  Content = barcode;
}

EDIT

Ok, so I made platformspecific code to handles this instead, until the issue has been resolved. So now my code is like this.

#if __IOS__

  var writer = new ZXing.Mobile.BarcodeWriter
  {
    Format = ZXing.BarcodeFormat.EAN_13,
    Options = new ZXing.Common.EncodingOptions
    {
      Width = 75,
      Height = 25,
      Margin = 30
    }
  };

  var b = writer.Write("2800100028014");

  Image m = new Image
  {
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    Source = ImageSource.FromStream(() => b.AsPNG().AsStream())
  };

  Content = m;
#endif
#if __ANDROID__

  ZXingBarcodeImageView barcode = new ZXingBarcodeImageView
  {
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
  };

  barcode.BarcodeFormat = ZXing.BarcodeFormat.EAN_13;
  barcode.BarcodeOptions.Height = 25;
  barcode.BarcodeOptions.Width = 75;
  barcode.BarcodeOptions.Margin = 20;
  barcode.BarcodeValue = "2800100028014";

  Content = barcode;
#endif

Solution

  • Ok, so this wasn't an issue in the package. Just needed to initialize it properly like this.

    On Android platform, my MainActivity.cs looks like this, it is the ZXing.Net that needed to be initialized:

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);
        global::ZXing.Net.Mobile.Forms.Android.Platform.Init();
        LoadApplication (new Test.App ());
        this.ActionBar.SetIcon(Android.Resource.Color.Transparent);
    }
    

    On iOS platform, my AppDelegat.cs looks like this, it is the ZXing.Net that needed to be initialized:

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init ();
        global::ZXing.Net.Mobile.Forms.iOS.Platform.Init();
        LoadApplication (new Test.App ());
        return base.FinishedLaunching (app, options);
    }