Introduction

Here, the basic requirement is to generate the Barcode or QR Code. We need to get some information from the user like what message they want to convert, code format, size of the bitmap, etc. There is no default library for this so, we need to install a plugin. Just write a few lines of code to generate 1D and 2D Code. The Barcode has different formats but I will demonstrate only a few code formats - Code 39, Code 128, AZTEC, and QR Code.

Android Output


Generate Barcode And QR Code In Xamarin Android
Let’s start.
Step 1

Create a Xamarin.Android application by going to Visual Studio >> New Project >> Android App. Click "Next".
Generate Barcode And QR Code In Xamarin Android
Here, let us give a project name, organization name, app compatibility, and app theme, then click "Create".
Generate Barcode And QR Code In Xamarin Android
Step 2
After project creation, first, we need to install a plugin. For this, go to Solution Explorer >> right-click Packages and select "Add packages". A new window will appear; at the top-right, search for ZXing.Net plugin and add this package.
Generate Barcode And QR Code In Xamarin Android
Step 3
Now, let’s code. First, open content_main.xml. For that, go to Solution Explorer >> Resource >> Layout >> double click to open content_main.xml. Add the following code to this file.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. app:layout_behavior="@string/appbar_scrolling_view_behavior"
  9. tools:showIn="@layout/activity_main">
  10. <TextView
  11. android:id="@+id/txtChooseStatic"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:layout_marginTop="10dp"
  15. android:layout_alignParentTop="true"
  16. android:text="Choose Encoding Method" />
  17. <Spinner
  18. android:id="@+id/spinner"
  19. android:layout_width="fill_parent"
  20. android:layout_marginTop="10dp"
  21. android:layout_height="wrap_content"
  22. android:layout_below="@+id/txtChooseStatic"
  23. android:prompt="@string/action_choose"/>
  24. <EditText
  25. android:id="@+id/plain_text_input"
  26. android:layout_height="wrap_content"
  27. android:layout_width="match_parent"
  28. android:layout_margin="10dp"
  29. android:layout_below="@+id/spinner"
  30. android:hint="Type Message to Convert"
  31. android:inputType="text"/>
  32. <ImageView
  33. android:layout_centerHorizontal="true"
  34. android:layout_marginTop="10dp"
  35. android:id="@+id/barcodeImage"
  36. android:layout_below="@+id/plain_text_input"
  37. android:layout_width="wrap_content"
  38. android:layout_height="wrap_content"/>
  39. <Button
  40. android:id="@+id/generate"
  41. android:background="#000000"
  42. android:textColor="#ffffff"
  43. android:layout_centerHorizontal="true"
  44. android:layout_width="wrap_content"
  45. android:padding="10dp"
  46. android:layout_marginTop="10dp"
  47. android:layout_below="@+id/barcodeImage"
  48. android:layout_height="wrap_content"
  49. android:textSize="15dp"
  50. android:text="Generate Code"/>
  51. </RelativeLayout>
Step 4
Next, open MainActivity.cs and add the following code to generate the barcode.
  1. using System;
  2. using System.IO;
  3. using Android.App;
  4. using Android.Content.PM;
  5. using Android.Graphics;
  6. using Android.OS;
  7. using Android.Runtime;
  8. using Android.Support.Design.Widget;
  9. using Android.Support.V4.App;
  10. using Android.Support.V4.Content;
  11. using Android.Support.V7.App;
  12. using Android.Views;
  13. using Android.Widget;
  14. using ZXing;
  15. using ZXing.Common;
  16. namespace BarCodeGenerator
  17. {
  18. [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
  19. public class MainActivity : AppCompatActivity
  20. {
  21. private TextView txtMessage;
  22. private string message;
  23. private static int size = 660;
  24. private static int small_size = 264;
  25. private Spinner spinnerValue;
  26. private string CodeType;
  27. protected override void OnCreate(Bundle savedInstanceState)
  28. {
  29. base.OnCreate(savedInstanceState);
  30. Xamarin.Essentials.Platform.Init(this, savedInstanceState);
  31. SetContentView(Resource.Layout.activity_main);
  32. Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
  33. SetSupportActionBar(toolbar);
  34. ImageView image = FindViewById<ImageView>(Resource.Id.barcodeImage);
  35. Button btnGenerate = FindViewById<Button>(Resource.Id.generate);
  36. txtMessage = FindViewById<TextView>(Resource.Id.plain_text_input);
  37. spinnerValue = FindViewById<Spinner>(Resource.Id.spinner);
  38. FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
  39. var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.selected_Code, Android.Resource.Layout.SimpleSpinnerItem);
  40. adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
  41. spinnerValue.Adapter = adapter;
  42. spinnerValue.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelect);
  43. fab.Click += FabOnClick;
  44. btnGenerate.Click += delegate
  45. {
  46. string[] PERMISSIONS =
  47. {
  48. "android.permission.READ_EXTERNAL_STORAGE",
  49. "android.permission.WRITE_EXTERNAL_STORAGE"
  50. };
  51. var permission = ContextCompat.CheckSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
  52. var permissionread = ContextCompat.CheckSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE");
  53. if (permission != Permission.Granted && permissionread != Permission.Granted)
  54. ActivityCompat.RequestPermissions(this, PERMISSIONS, 1);
  55. try
  56. {
  57. if (permission == Permission.Granted && permissionread == Permission.Granted)
  58. {
  59. BitMatrix bitmapMatrix = null;
  60. message = txtMessage.Text.ToString();
  61. switch (CodeType)
  62. {
  63. case "QR Code":
  64. bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, size, size);
  65. break;
  66. case "PDF 417":
  67. bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.PDF_417, size, small_size);
  68. break;
  69. case "CODE 128":
  70. bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_128, size, small_size);
  71. break;
  72. case "CODE 39":
  73. bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_39, size, small_size);
  74. break;
  75. case "AZTEC":
  76. bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.AZTEC, size, small_size);
  77. break;
  78. }
  79. var width = bitmapMatrix.Width;
  80. var height = bitmapMatrix.Height;
  81. int[] pixelsImage = new int[width * height];
  82. for (int i = 0; i < height; i++)
  83. {
  84. for (int j = 0; j < width; j++)
  85. {
  86. if (bitmapMatrix[j, i])
  87. pixelsImage[i * width + j] = (int)Convert.ToInt64(0xff000000);
  88. else
  89. pixelsImage[i * width + j] = (int)Convert.ToInt64(0xffffffff);
  90. }
  91. }
  92. Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
  93. bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);
  94. var sdpath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
  95. var path = System.IO.Path.Combine(sdpath, "logeshbarcode.jpg");
  96. var stream = new FileStream(path, FileMode.Create);
  97. bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
  98. stream.Close();
  99. image.SetImageBitmap(bitmap);
  100. }
  101. else
  102. {
  103. Console.WriteLine("No Permission");
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. Console.WriteLine($"Exception {ex} ");
  109. }
  110. };
  111. }
  112. private void SpinnerItemSelect(object sender, AdapterView.ItemSelectedEventArgs e)
  113. {
  114. Spinner spinner = (Spinner)sender;
  115. CodeType = (string)spinner.GetItemAtPosition(e.Position);
  116. }
  117. public override bool OnCreateOptionsMenu(IMenu menu)
  118. {
  119. MenuInflater.Inflate(Resource.Menu.menu_main, menu);
  120. return true;
  121. }
  122. public override bool OnOptionsItemSelected(IMenuItem item)
  123. {
  124. int id = item.ItemId;
  125. if (id == Resource.Id.action_settings)
  126. {
  127. return true;
  128. }
  129. return base.OnOptionsItemSelected(item);
  130. }
  131. private void FabOnClick(object sender, EventArgs eventArgs)
  132. {
  133. View view = (View)sender;
  134. Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
  135. .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
  136. }
  137. public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
  138. {
  139. Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  140. base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  141. }
  142. }
  143. }
Step 5
Finally, the application requires storage read and write permissions. For that, go to Solution Explorer >> Properties >> AndroidManifest.xml file. Check the permissions for External Storage Read and Write.
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 6
Now, press F5 to run the application. The output will be like below.
Generate Barcode And QR Code In Xamarin Android
You can get the full source code from here.