Generate Barcode and QR Code in Xamarin Android


Introduction

           In this article, we can discuss how to generate 1D and 2D Barcode in Xamarin Android application. Here basic requirement to generate Barcode or QR Code, we need to get some information form user like what message you want to convert, Code format, size of the bitmap. There is no default library for this. so, we need to install a plugin for this. Just write a few lines of code to generate 1D and 2D Code. The Barcode has a different format but I demonstrate some few code formats - Code 39, Code 128, AZTEC and QR Code. 


Android Output:



Let’s start 😊

Step 1:

     Create can create Xamarin.Android Application by going to Visual Studio New Project >> Android App click next.


Here gives a project name, organization name, app compatibility, and app theme, then click Create.




Step 2:
     After project creation, first we need to install a plugin for this by going to Solution Explorer >> right-click Packages and select Add packages, then new windows will appear, here right-side top search ZXing.Net plugin and add this package.



Step 3:
     Now, let’s coding. First open content_main.xml. For that, go to Solution Explorer >> Resource >> Layout >> double click to open content_main.xml. add the following given code to this file.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">
    <TextView
        android:id="@+id/txtChooseStatic"
       android:layout_width="fill_parent"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="10dp"
       android:layout_alignParentTop="true"
       android:text="Choose Encoding Method" />  
    <Spinner  
       android:id="@+id/spinner"  
       android:layout_width="fill_parent"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content"
       android:layout_below="@+id/txtChooseStatic"
       android:prompt="@string/action_choose"/>
    <EditText
         android:id="@+id/plain_text_input"
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_margin="10dp"
         android:layout_below="@+id/spinner"
         android:hint="Type Message to Convert"
         android:inputType="text"/>
    <ImageView
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:id="@+id/barcodeImage"
        android:layout_below="@+id/plain_text_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/generate"
        android:background="#000000"
        android:textColor="#ffffff"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/barcodeImage"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="Generate Code"/>

</RelativeLayout>

Step 4:
    Next open, MainActivity.cs and add the following code to generate bar code. For that, open Solution Explorer >> MainActivity.cs. This page code gives below.


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
using System;
using System.IO;
using Android.App;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using ZXing;
using ZXing.Common;

namespace BarCodeGenerator
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private TextView txtMessage;
        private string message;
        private static int size = 660;
        private static int small_size = 264;
        private Spinner spinnerValue;
        private string CodeType;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            ImageView image = FindViewById<ImageView>(Resource.Id.barcodeImage);
            Button btnGenerate = FindViewById<Button>(Resource.Id.generate);
            txtMessage = FindViewById<TextView>(Resource.Id.plain_text_input);
            spinnerValue = FindViewById<Spinner>(Resource.Id.spinner);
            FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);

            var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.selected_Code, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerValue.Adapter = adapter;
            spinnerValue.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelect);
            fab.Click += FabOnClick;

            btnGenerate.Click += delegate
            {
                string[] PERMISSIONS =
                {
                    "android.permission.READ_EXTERNAL_STORAGE",
                    "android.permission.WRITE_EXTERNAL_STORAGE"
                };

                var permission = ContextCompat.CheckSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
                var permissionread = ContextCompat.CheckSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE");

                if (permission != Permission.Granted && permissionread != Permission.Granted)
                    ActivityCompat.RequestPermissions(this, PERMISSIONS, 1);

                try
                {
                    if (permission == Permission.Granted && permissionread == Permission.Granted)
                    {
                        BitMatrix bitmapMatrix = null;
                        message = txtMessage.Text.ToString();

                        switch (CodeType)
                        {
                            case "QR Code":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, size, size);
                                break;
                            case "PDF 417":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.PDF_417, size, small_size);
                                break;
                            case "CODE 128":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_128, size, small_size);
                                break;
                            case "CODE 39":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_39, size, small_size);
                                break;
                            case "AZTEC":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.AZTEC, size, small_size);
                                break;
                        }

                        var width = bitmapMatrix.Width;
                        var height = bitmapMatrix.Height;
                        int[] pixelsImage = new int[width * height];

                        for (int i = 0; i < height; i++)
                        {
                            for (int j = 0; j < width; j++)
                            {
                                if (bitmapMatrix[j, i])
                                    pixelsImage[i * width + j] = (int)Convert.ToInt64(0xff000000);
                                else
                                    pixelsImage[i * width + j] = (int)Convert.ToInt64(0xffffffff);

                            }
                        }

                        Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                        bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);

                        var sdpath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
                        var path = System.IO.Path.Combine(sdpath, "logeshbarcode.jpg");
                        var stream = new FileStream(path, FileMode.Create);
                        bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                        stream.Close();

                        image.SetImageBitmap(bitmap);
                    }
                    else
                    {
                        Console.WriteLine("No Permission");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception {ex} ");
                }
            };
        }

        private void SpinnerItemSelect(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;
            CodeType = (string)spinner.GetItemAtPosition(e.Position);
        }

        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.menu_main, menu);
            return true;
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            int id = item.ItemId;
            if (id == Resource.Id.action_settings)
            {
                return true;
            }

            return base.OnOptionsItemSelected(item);
        }

        private void FabOnClick(object sender, EventArgs eventArgs)
        {
            View view = (View)sender;
            Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
                .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}



Step 5:

         Finally, the application required storage read and write permission. For that, go to Solution Explorer >> Properties >> Open AndroidManifest.xml file. Check the Permissions of External Storage Read and Write Permission.


1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Step 6:

        Now, press F5 to run the application. The Output like below.




Full Source Code Here

Thank you. Suggestion to the command below.

Charts in Xamarin Forms Application


Introduction                        Displaying charts in mobile apps has always been a great way to offer users a clear overview of numerical data. I want this task to be as easy as writing a few lines of code, but I couldn't find a straight-forward way to achieve this. This is why I started exploring SkiaSharp and created Microcharts.
NuGet Package : Xamarin.Forms = search "Microcharts.Forms"
   
This simple plugin can display microcharts in Xamarin.Forms.


Available charts Microcharts.Forms Plugin
  • Barchart
  • PointChart
  • LineChart
  • DonutChart
  • RadialGaugeChart
  • RadarChart
Chart Types
1. BarChart

  1.  Chartview.Chart =  new BarChart(){Entries = entries};

2. PointChart

  1. Chartview.Chart =  new PointChart(){Entries = entries};

3. LineChart

  1. Chartview.Chart =  new LineChart(){Entries = entries};

4. DonutChart

  1. Chartview.Chart =  new DonutChart(){Entries = entries}; 

5. RadialGaugeChart
  1. Chartview.Chart =  new RadialGaugeChart(){Entries = entries}; 



6. RadarChart
  1. Chartview.Chart =  new RadartChart(){Entries = entries};

Step 1                 You can create Xamarin.Forms app by going to File >> New >> Visual C# >> Cross Platform >> Cross Platform App (Xamarin.Native or Xamarin.Forms), give the application name and press OK.

(Project name: MicrochartsApp)
Step 2      Now, add the following NuGet Package for your projects.
  • Microcharts.Forms

    For that, go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for the Solution". Now, select the following NuGet Package, select your project, and install it.
  • Microcharts.Forms
Step 3
   To display a chart, we'll need to host it in a ChartView.
      
    After installing NuGet packages, add a ChartView control to your project. For that, go to Solution Explorer >> MicrochartsApp(PCL) >>> Double-click on MainPage.xaml. After opening this, you can add assembly and XAML code to your project. Here is the code for this page.
Assembly
  1. xmlns:forms="clr-namespace:Microcharts.Forms;assembly=Microcharts.Forms"
XAML code
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:MicrochartsApp"  
  5.              x:Class="MicrochartsApp.MainPage"  
  6.              xmlns:forms="clr-namespace:Microcharts.Forms;assembly=Microcharts.Forms">  
  7.     <ScrollView>   
  8.         <StackLayout Orientation="Vertical">  
  9.           
  10.         <forms:ChartView x:Name="Chart1"  
  11.                                HeightRequest="150"/>  
  12.         <forms:ChartView x:Name="Chart2"  HeightRequest="150" />  
  13.         <forms:ChartView x:Name="Chart3"  
  14.                              HeightRequest="150"/>  
  15.         <forms:ChartView x:Name="Chart4"  
  16.                              HeightRequest="150"/>  
  17.         <forms:ChartView x:Name="Chart5"  
  18.                              HeightRequest="150"/>  
  19.         <forms:ChartView x:Name="Chart6"                                                          HeightRequest="160"/>  
  20.         </StackLayout>  
  21.     </ScrollView>  
  22. </ContentPage>
Step 4          In this step, add data entries. For that, open Solution Explorer >> MicrochartsApp(PCL) >>click open MainPage.xaml.cs. This class code is given below.

           Every chart displays via Microcharts and consumes a set of data entries. They will always have the same structure regardless of the chart type that you want to display.
Each entry
  •  Floating number representing it's value is required.
  •  Label - what your entry is associated with.
  •  ValueLabel - format your value
  •  Color - entry
  1. using Microcharts;  
  2. using SkiaSharp;  
  3. using Microcharts.Forms;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using Xamarin.Forms;  
  10. using Entry = Microcharts.Entry;  
  11.   
  12.   
  13. namespace MicrochartsApp  
  14. {  
  15.     public partial class MainPage : ContentPage  
  16.     {  
  17.         List<Entry> entries = new List<Entry>  
  18.         {  
  19.             new Entry(200)  
  20.             {  
  21.                 Color=SKColor.Parse("#FF1943"),  
  22.                 Label ="January",  
  23.                 ValueLabel = "200"  
  24.             },  
  25.             new Entry(400)  
  26.             {  
  27.                 Color = SKColor.Parse("00BFFF"),  
  28.                 Label = "March",  
  29.                 ValueLabel = "400"  
  30.             },  
  31.             new Entry(-100)  
  32.             {  
  33.                 Color =  SKColor.Parse("#00CED1"),  
  34.                 Label = "Octobar",  
  35.                 ValueLabel = "-100"  
  36.             },  
  37.             };  
  38.         public MainPage()  
  39.         {  
  40.             InitializeComponent();  
  41.   
  42.               
  43.             Chart1.Chart = new RadialGaugeChart() { Entries = entries };  
  44.             Chart2.Chart = new LineChart() { Entries = entries };  
  45.             Chart3.Chart = new DonutChart() { Entries = entries };  
  46.             Chart4.Chart = new BarChart() { Entries = entries };  
  47.             Chart5.Chart = new PointChart() { Entries = entries };  
  48.             //Chart6.Chart = new RadarChart() { Entries = entries };  
  49.         }  
  50.     }  
Step 5
Now, go to "Build" menu and configure your startup project. After configuring, run your project. You will have the result like below.



Finally, we have successfully created Xamarin.Forms Microcharts application.




Featured Post

Generate Barcode and QR Code in Xamarin Android

Introduction            In this article, we can discuss how to generate 1D and 2D Barcode in Xamarin Android application. Here basic...