Showing posts with label .net maui. Show all posts

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

Dynamic Status Bar in .NET MAUI Dynamic Status Bar in .NET MAUI

A blog about android developement

.net maui

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Dynamic Status Bar in .NET MAUI project.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 buttons like in the following code block.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiStatusBarBehaviour.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                Text="Blue"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnBlueClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Green"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnGreenClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Default"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnDefaultClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Methods:

To implement this, we can implement in the following methodlogies.

  • Applying Behaviour in XAML.
  • Applying Behaviour in Code behind.
  • Applying without behaviour in Code behind.

In this article, we are going to see "Applying without behaviour in Code behind.".

  • Just install the .NET MAUI community toolkit to your project.
    Install-Package CommunityToolkit.Maui -Version 3.1.0
  • Add it to the MauiProgram.cs
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp<App>()
    .UseMauiCommunityToolkit()
    .ConfigureFonts(fonts => {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    });
  • Add event in code behind for each button click and apply the below code.
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(statusBarColor);
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetStyle(StatusBarStyle.LightContent);

Full Code:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/statusbar-behavior

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and ...

Localisation in .NET MAUI Localisation in .NET MAUI

A blog about android developement

.net maui

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Localisation in .NET MAUI project.


Advantages of Localisation

  • Localisation improves user experience by providing content and language that is culturally relevant and easily understandable to users in different regions, increasing engagement and satisfaction.
  • It expands market reach by making products or services accessible to a global audience, tapping into new markets and driving business growth.
  • Localisation helps build trust and credibility with international customers by demonstrating a commitment to their specific needs and preferences, fostering stronger relationships and customer loyalty.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - 2 labels, and button like in the following code block.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:resource="clr-namespace:MauiLocalization"
             x:Class="MauiLocalization.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.Helloworld}"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.WelcomeNote}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Change to Tamil"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Create RESX file

In this step, we will see the steps to create RESX file.

  • In the Solution Explorer, right-click on the project or folder where you want to add the RESX file.
  • Select "Add" from the context menu and then choose "New Item" or "New Folder" if you want to organize your resources in a separate folder.
  • In the "Add New Item" dialog box, search for "Resource File" or navigate to "General" -> "Text File" and name the file with the .resx extension.
  • Click the "Add" button to create the resource file.
  • We created two resources file. One is default and another one prefixed with the language code.
    1. LangResources.resx
    2. LangResources.ta.resx (Contains the resource equivalent in tamil)

RESX Files in XAML

  • To utilize your resources, you first need to import the XML namespace associated with them.
  • xmlns:resource="clr-namespace:MauiLocalization"
  • Then, you can access your strings by using the [x:Static](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/xaml-markup-extensions#the-xstatic-markup-extension) markup extension, treating them as properties.
    Text="{x:Static resource:LangResources.Helloworld}"

Language Update

  • Add click event to the button to change language based on the language code of the resource file.
    private void OnCounterClicked(object sender, EventArgs e)
    {
    	if (CounterBtn.Text.Contains("Tamil"))
    	{
    		LangResources.Culture = new CultureInfo("ta");
    		CounterBtn.Text = "Change to English";
    	}
    	else
    	{
    		LangResources.Culture = CultureInfo.InvariantCulture;
    		CounterBtn.Text = "Change to Tamil";
    	}
    	App.Current.MainPage = new MainPage();
    }
  • Here, "App.Current.MainPage = new MainPage();" is used to refresh page once the language changed
  • Then, we will add the below block in the page constructor to retain the language change once the button clicked and page refreshed.
    if (LangResources.Culture != null && LangResources.Culture.TwoLetterISOLanguageName.Contains("ta"))
    {
    	CounterBtn.Text = "Change to English";
    }
    else
    {
    	CounterBtn.Text = "Change to Tamil";
    }

Full Code:

Demo

Android:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://learn.microsoft.com/en-us/dotnet/core/extensions/resources

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C#...

File Picker in .NET MAUI File Picker in .NET MAUI

A blog about android developement

.net maui

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement a File Picker in the .NET MAUI project.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - button, image, and label like in the following code block.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiFilePicker.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30"
            VerticalOptions="Start">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Label x:Name="outputText"
                   Padding="10"/>
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select images from device.
  • Image - used to display the selected image.
  • Label - used to display the file path once the image selected through file picker.

Functional part

  • Add a click event for the button to select the image like below.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	outputText.Text = imageSource;
    }

    Here,

    • FileTypes: The default file types available for selection in the FilePicker are FilePickerFileType.Images, FilePickerFileType.Png, and FilePickerFileType.Videos. However, if you need to specify custom file types for a specific platform, you can create an instance of the FilePickerFileType class. This allows you to define the desired file types according to your requirements.
    • PickerTitle: The PickOptions.PickerTitle is presented to the user and its behavior varies across different platforms.

    Full Code:

    Demo

    Android:
    android
    Windows:
    windows

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

    References

    https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/file-picker

.NET MAUI, a powerful platform for developing cross-platform mobile applications, provides a seamless way to incorporate Toast fun...

Toast in .NET MAUI Toast in .NET MAUI

A blog about android developement

.net maui

.NET MAUI, a powerful platform for developing cross-platform mobile applications, provides a seamless way to incorporate Toast functionality into your app. With the aid of the appropriate tools and resources, implementing an Toast in .NET MAUI using the .NET MAUI Community Toolkit is a straightforward process. In this tutorial, we will guide you through the necessary steps to successfully integrate Toast into your .NET MAUI application.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

.NET MAUI Community Toolkit is the key to achieve drawing in our App is to use Community.ToolKit.Maui NuGet package. It is a collection of reusable elements such as animations, behaviors converters, among others, for developing applications for iOS, Android, macOS and WinUI using MAUI.


Install .NET MAUI Community Toolkit

  • Install .NET MAUI Community Toolkit nuGet package on your .NET MAUI application.
  • Now initialize the plugin. Go to your MauiProgram.cs file. In the CreateMauiApp method, place in the .UseMauiApp<App>() line and just below it add the following line of code.
var builder = MauiApp.CreateBuilder();
builder
	.UseMauiApp<App>()
	.UseMauiCommunityToolkit()
	.ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            await Toast.Make("Hi, How are you?",
                      ToastDuration.Long,
                      16)
                .Show(cancellationTokenSource.Token);
  • The methods Make() and Show() are essential for displaying Toast messages on the screen. Each of these methods possesses specific attributes that facilitate the configuration of the Toast. Let's delve into a closer examination of these attributes.
  • Make:

    The Make() method is responsible for creating the Toast and requires the following parameters:
    • Text: This is a mandatory parameter represents the message that will be displayed in the Toast.
    • Duration: This parameter specifies the exact duration for which the Toast message will be shown on the screen before fading away. It is an optional parameter and it's default ToastDuration type is ToastDuration.Short:
    • TextSize: This parameter is an optional paramter to set the text size of the Toast. Default value of this parameter is 14 and it's type is double.

    Show:

    This method is responsible for displaying the requested Toast message on the screen.

    Full Code:

    Demo

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

    The idea behind this tutorial is from "AskXammy"

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's eas...

Avatar View in .NET MAUI Community Toolkit Avatar View in .NET MAUI Community Toolkit

A blog about android developement

.net maui

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to implement Avatar View to your app. In this tutorial, we'll walk you through the steps for adding Avatar View in .NET MAUI using .NET MAUI Community Toolkit.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

.NET MAUI Community Toolkit is the key to achieve drawing in our App is to use Community.ToolKit.Maui NuGet package. It is a collection of reusable elements such as animations, behaviors converters, among others, for developing applications for iOS, Android, macOS and WinUI using MAUI.


Install .NET MAUI Community Toolkit

  • Install .NET MAUI Community Toolkit nuGet package on your .NET MAUI application.
  • Now initialize the plugin. Go to your MauiProgram.cs file. In the CreateMauiApp method, place in the .UseMauiApp<App>() line and just below it add the following line of code.
var builder = MauiApp.CreateBuilder();
builder
	.UseMauiApp<App>()
	.UseMauiCommunityToolkit()
	.ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});
  • A graphical representation known as an avatar is connected to a particular user in order to identify them. This is frequently utilised in programmes that we use every day, therefore it's crucial that you have access to the tools that will enable you to accomplish it. This tutorial will teach you how to quickly and easily construct the.NET Maui Community Toolkit AvatarView!
  • Add the following namespace in the xaml file.
    xmlns:toolkit="clr-namespace:CommunityToolkit.Maui.Views;assembly=CommunityToolkit.Maui"
  • Once the namespace added, you have to add the AvatarView tag with the properties that we required like below.
    <toolkit:AvatarView Text="AM"
    					FontSize="30"
                        TextColor="White"
                        BackgroundColor="Green"
                        BorderColor="White"
                        BorderWidth="5" 
                        HeightRequest="150"
                        WidthRequest="150"                                
                        CornerRadius="120"
                        ImageSource="dotnet_bot.png"/>
  • AvatarView’s properties

    • Text: This property help to set the text to the view
    • ImageSource: This property help to set the image to the view
    • CornerRadius: Determines the shape of the control. The properties can be set in the below ways.
    • Sample 1: CornerRadius="120"
    • Sample 2: CornerRadius="120,40,120,40"

    Full Code:

    Demo

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's...

Signature Pad using .NET MAUI Community Toolkit Signature Pad using .NET MAUI Community Toolkit

A blog about android developement

.net maui

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to add signature pad functionality to your app. In this tutorial, we'll walk you through the steps of signature pad in .NET MAUI using .NET MAUI Community Toolkit.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

.NET MAUI Community Toolkit is the key to achieve drawing in our App is to use Community.ToolKit.Maui NuGet package. It is a collection of reusable elements such as animations, behaviors converters, among others, for developing applications for iOS, Android, macOS and WinUI using MAUI.


Install .NET MAUI Community Toolkit

  • Install .NET MAUI Community Toolkit nuGet package on your .NET MAUI application.
  • Now initialize the plugin. Go to your MauiProgram.cs file. In the CreateMauiApp method, place in the .UseMauiApp<App>() line and just below it add the following line of code.
var builder = MauiApp.CreateBuilder();
builder
	.UseMauiApp<App>()
	.UseMauiCommunityToolkit()
	.ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});
  • DrawView is a class provided by Community.Toolkit.Maui which is responsible for providing a surface that allows drawing lines through touch or mouse interaction.
  • Add the following namespace in the xaml file.
    xmlns:mct="clr-namespace:CommunityToolkit.Maui.Views;assembly=CommunityToolkit.Maui"
  • Once the namespace added, you have to add the DrawingView tag with the properties that we required like below.
    <mct:DrawingView x:Name="DrawBoard"
                        LineColor="Black"
                        LineWidth="5" 
                        HorizontalOptions="FillAndExpand"
                        VerticalOptions="FillAndExpand"
                        HeightRequest="250"
                        IsMultiLineModeEnabled="True"
                        DrawingLineCompleted="DrawBoard_DrawingLineCompleted"
                        BackgroundColor="AliceBlue"/>
  • DrawingView’s properties

    • WidthRequest and HeightRequest: These properties help to set the width and height respectively.
      Keep in mind that you must add both properties to your DrawingView in order for it to be displayed correctly in your app.
    • LineColor: It’s the color of the drawing line.
    • LineWidth: It’s the width of the drawing line.
    • IsMultiLineModeEnabled: By default, the DrawingView allows only one stroke to be drawn at a time. The IsMultiLineModeEnabled property allows you to change this and draw multiple lines at once. It receives Bool values. To activate it you need to set the value to True.

    Cleaning the DrawView:

    • If you want to clear the DrawView, add the following
      DrawBoard.Lines.Clear();
    • The clear function can be called using the button click event and can be called like below
      <Button Text="Clear Board" 
                          Clicked="Button_Clicked"/>
      void Button_Clicked(System.Object sender, System.EventArgs e)
      {
      	DrawBoard.Lines.Clear();
      }

    Previewing the signature or drawing from DrawView:

    • Add an Image control to your XAML.
    • <Image x:Name="ImageView"
             WidthRequest="200"
             HeightRequest="200"/>
  • Add an event for DrawingLineCompleted in the code behind.
  • private void DrawBoard_DrawingLineCompleted(System.Object sender, CommunityToolkit.Maui.Core.DrawingLineCompletedEventArgs e)
    {
    	ImageView.Dispatcher.Dispatch(async() =>
    	{
    		var stream = await DrawBoard.GetImageStream(300, 300);
    		ImageView.Source = ImageSource.FromStream(() => stream);
    	});
    }
Full Code:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it'...

.Net MAUI - QR Code Generator .Net MAUI - QR Code Generator

A blog about android developement

.net maui

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to add barcode scanning functionality to your app. In this tutorial, we'll walk you through the steps of implementing a QR Code Generator in .NET MAUI using the Codebude - QR Coder plugin.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

QRCoder is a simple library, written in C#.NET, which enables you to create QR codes. First, we need to add the QR Coder library to our project as a dependency. To do this, open the NuGet Package Manager and search for "QRCoder". Install the package in your .NET MAUI project.


Install QRCoder

Install QRCoder nuGet package on your .NET MAUI application.

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(InputText.Text, QRCodeGenerator.ECCLevel.L);
PngByteQRCode qRCode = new PngByteQRCode(qrCodeData);
byte[] qrCodeBytes = qRCode.GetGraphic(20);
QrCodeImage.Source = ImageSource.FromStream(() => new MemoryStream(qrCodeBytes));

The above lines only need to generate the QR code for your mobile application.

How to change the color of your QR code

The GetGraphics-method has some more overloads. The first two enable you to set the color of the QR code graphic. One uses Color-class-types, the other HTML hex color notation.

//Set color by using Color-class types
Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.DarkRed, Color.PaleGreen, true);

//Set color by using HTML hex color notation
Bitmap qrCodeImage = qrCode.GetGraphic(20, "#000ff0", "#0ff000");
Full Code of MainPage:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it'...

.Net MAUI - Zxing Barcode Scanner .Net MAUI - Zxing Barcode Scanner

A blog about android developement

.net maui

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to add barcode scanning functionality to your app. In this tutorial, we'll walk you through the steps of implementing a barcode scanner in .NET MAUI using the ZXing.Net.MAUI plugin.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

The successor to ZXing.Net.Mobile: barcode scanning and generation for .NET MAUI applications. First, we need to add the ZXing.Net.MAUI library to our project as a dependency. To do this, open the NuGet Package Manager and search for "ZXing.Net.MAUI". Install the package in your .NET MAUI project.

Install ZXing.Net.MAUI

Install ZXing.Net.MAUI NuGet package on your .NET MAUI application. Make sure to initialize the plugin first in your MauiProgram.cs, see below

// Add the using to the top
using ZXing.Net.Maui;

// ... other code 

public static MauiApp Create()
{
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp&lt;App&gt;()
    .UseBarcodeReader(); // Make sure to add this line

return builder.Build();
}

Now we just need to add the right permissions to our app metadata. Find below how to do that for each platform.

Android

For Android go to your "AndroidManifest.xml" file (under the Platforms\Android folder) and add the following permissions inside of the "manifest" node.

<uses-permission android:name="android.permission.CAMERA" />

iOS

For iOS go to your "info.plist" file (under the Platforms\iOS folder) and add the following permissions inside of the "dict" node:

<key>NSCameraUsageDescription</key>
<string>This app uses barcode scanning to...</string>

Make sure that you enter a clear and valid reason for your app to access the camera. This description will be shown to the user.

Windows

Windows is not supported at this time for barcode scanning. You can however use the barcode generation. No extra permissions are required for that. For more information on permissions, see the Microsoft Docs.

Using ZXing.Net.Maui

If you're using the controls from XAML, make sure to add the right XML namespace in the root of your file, e.g:

xmlns:zxing="clr-namespace:ZXing.Net.Maui.Controls;assembly=ZXing.Net.MAUI"
<zxing:CameraBarcodeReaderView
  x:Name="cameraBarcodeReaderView"
  BarcodesDetected="BarcodesDetected" />
Full Code of MainPage.xaml:

Configure Reader options

cameraBarcodeReaderView.Options = new BarcodeReaderOptions
{
  Formats = BarcodeFormats.OneDimensional,
  AutoRotate = true,
  Multiple = true
};

Toggle Torch

cameraBarcodeReaderView.IsTorchOn = !cameraBarcodeReaderView.IsTorchOn;

Flip between Rear/Front cameras

cameraBarcodeReaderView.CameraLocation
  = cameraBarcodeReaderView.CameraLocation == CameraLocation.Rear ? CameraLocation.Front : CameraLocation.Rear;

Handle detected barcode(s)

protected void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
{
  foreach (var barcode in e.Results)
    Console.WriteLine($"Barcodes: {barcode.Format} -> {barcode.Value}");
}
Full code of MainPage.xaml.cs

Demo

Full Code:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.