QR CODE Generator: Xamarin.Forms

This article shows how to create a barcode scanner in all the three platforms: Android, iOS and Windows using Xamarin.Forms.

In my last article I explained how to create a barcode scanner in Xamarin.Forms. Here I'm going to explain something about a Barcode \ QR Code Generator.

For creating the QR Code Generator I'm going to use the same NuGet package, Arc.Barcodes, a cross-platform creator built on top of ZXing.Net.Mobile to allow for easy cross-platform access from Shared/PCL core libraries that I have used to create the Barcode Scanner.



Now we want to initialize the corresponding NuGet package in each platform-specific startup classes.

In Android, on MainActivity.cs call:

global::Acr.BarCodes.BarCodes.Init(() => (Activity)Xamarin.Forms.Forms.Context); before calling LoadApplication();.

In iOS, on AppDelegate.cs call global::Xamarin.Forms.Forms.Init(); before calling LoadApplication();.

In Windows Phone, on MainPage.cs call global::Xamarin.Forms.Forms.Init(); before calling LoadApplication();.

Now we can create a button to initialize the event and Image View to load the QR Code and most importantly we must add an entry that will carry the value that will be carried by the QR Code.

  1. var btnCreateQR = new Button { Text = "Genrate" };  
  2. var imgCode = new Image();  
  3. var txtBarcode = new EntryCell { Label = "Value " };  
Now add the following set of code for the click event of the button to generate the QR Code and load in the Image View depending on the value\message given in the Entry cell.
  1. btnCreateQR.Clicked += (sender, e) =>  
  2. {  
  3.     try  
  4.     {  
  5.         var QRstream = BarCodes.Instance.Create(new BarCodeCreateConfiguration  
  6.         {  
  7.             Format = BarCodeFormat.QR_CODE,  
  8.             BarCode = txtBarcode.Text.Trim(),  
  9.             Width = 200,  
  10.             Height = 200  
  11.         }  
  12.         );  
  13.         txtBarcode.LabelColor = Color.White;  
  14.         imgCode.Source = ImageSource.FromStream(() => QRstream );  
  15.     }  
  16.     catch (Exception ex)  
  17.     {  
  18.         txtBarcode.LabelColor = Color.Red;  
  19.         System.Diagnostics.Debug.WriteLine(ex.ToString());  
  20.         DisplayAlert("Alert""Enter value that want to be carried in the QR Code""OK");  
  21.     }  
  22. };  




You can refer to the sample project attached with this for more details. Also, you can generate a Barcode, Data Matrix, Maxi code and so on, using the same logic.


Similar Articles