Android 15: Revolutionizing Mobile Experiences Android 15, codenamed Vanilla Ice Cream , was a significant leap forward in mobile OS innov...

Exploring Android 15 and the First Developer Preview of Android 16 Exploring Android 15 and the First Developer Preview of Android 16

A blog about android developement


Android 15: Revolutionizing Mobile Experiences

Android 15, codenamed Vanilla Ice Cream, was a significant leap forward in mobile OS innovation. Released earlier this year, it focused on delivering enhanced security, communication, and usability features for both everyday users and enterprise environments.

Key Features in Android 15:

  1. Private Space:
    Android 15 introduced Private Space, a virtual sandbox within the OS. This feature allows users to store sensitive files, apps, and data separately from the main environment, ensuring confidentiality. It's especially useful for professionals managing personal and work accounts on the same device.

  2. Enhanced Satellite Messaging:
    Taking connectivity to the next level, Android 15 supports satellite communication. While initially limited to premium devices, this feature ensures users remain connected even in remote or offline areas, marking a step forward in global communication capabilities.

  3. Partial Screen Recording:
    This innovative tool lets users record specific sections of their screen instead of the entire display. Ideal for sharing specific app workflows or sensitive content without revealing everything on-screen, it became a favorite among tech influencers and educators.

  4. Advanced Security Measures:
    Android 15 strengthened device security by including monthly security patches, encrypted backup improvements, and app activity transparency, ensuring user safety against modern digital threats.

  5. Performance Optimizations:
    With improved energy efficiency and reduced background process consumption, Android 15 extended battery life and boosted performance, especially on mid-range devices.


Android 16 Developer Preview: A Glimpse into the Future

Android 16 aims to build on Android 15’s solid foundation with groundbreaking improvements and cutting-edge technology. The first developer preview teases several enhancements that cater to developers and end-users alike.

What’s New in Android 16?

  1. AI-Enhanced Personalization:
    Android 16 integrates artificial intelligence deeply into the OS to adapt to individual usage patterns. From predictive app suggestions to dynamic interface adjustments, AI creates a more intuitive user experience.

  2. Cross-Device Harmony:
    Google is focusing on seamless cross-device operations, making it easier to transition between Android-powered smartphones, tablets, and wearable devices. Developers can leverage new APIs to build apps that offer consistent experiences across device ecosystems.

  3. Sustainability and Efficiency:
    The latest version takes sustainability seriously by introducing features that optimize energy consumption. Enhanced battery management tools and smarter resource allocation extend device life and reduce carbon footprints.

  4. Advanced Accessibility Features:
    Accessibility tools are getting a major upgrade, ensuring inclusivity for all users. Enhanced voice control, real-time transcription, and assistive gesture navigation are some of the highlights aimed at supporting diverse user needs.

  5. Developer-Centric Updates:
    Android 16 offers new tools to developers, including improvements to Jetpack Compose for creating responsive UI designs, updated debugging tools, and extended support for foldable and large-screen devices.

Why Developers Should Explore the Preview:

The first developer preview is a goldmine for app creators, allowing them to adapt their apps early to leverage Android 16's new capabilities. From API testing to performance benchmarking, this is a pivotal moment for the developer community to innovate alongside the OS.


Conclusion

Android 15 and Android 16 demonstrate Google’s unwavering commitment to enhancing the mobile experience. While Android 15 brought essential upgrades in security, connectivity, and usability, Android 16 pushes boundaries with AI-driven innovation and sustainability. Developers and users can look forward to a transformative era in mobile technology as these advancements become mainstream.

For developers, now is the time to dive into the Android 16 Developer Preview and explore its offerings to craft the next generation of apps that define the Android experience.


References

Android 15 Features

Android 16 Features

Image Generated using Chat GPT & DALL-E

In an exciting development for .NET MAUI, Syncfusion has made significant open-source contributions by releasing 14 essential UI component...

.NET MAUI Welcomes Syncfusion Open-source Contributions .NET MAUI Welcomes Syncfusion Open-source Contributions

A blog about android developement

In an exciting development for .NET MAUI, Syncfusion has made significant open-source contributions by releasing 14 essential UI components for free, empowering developers to enhance their applications. These components, found on GitHub and accessible via NuGet, include popular elements like Shimmer and offer capabilities for improved interactivity and visual appeal in .NET MAUI projects. This collaboration underscores Syncfusion’s commitment to the .NET ecosystem and signals a robust future for cross-platform development.


Syncfusion’s contributions align with Microsoft’s broader strategy to expand .NET MAUI’s open-source potential, paving the way for additional community involvement and accelerating the platform’s maturity. A noteworthy part of this collaboration is the ongoing support from Syncfusion for any potential issues and their active involvement in refining the developer experience.


In addition to these components, Microsoft and Syncfusion are working on introducing a new .NET MAUI project template with .NET 9. This template will come preconfigured with Syncfusion’s UI tools, alongside other third-party toolkits, to streamline project setup for developers. This streamlined experience will make it easier for developers to create well-structured, cross-platform applications that perform seamlessly on multiple devices.


Overall, this partnership demonstrates how .NET MAUI is evolving with rich community-driven contributions and shows promising advancements for developers aiming to build sophisticated, cross-platform mobile and desktop applications.


For more details, you can read the original blog post here.

 

 

Adding custom fonts in .NET MAUI (Multi-platform App UI) is a powerful way to improve your app’s design and branding, making it stand ...

How to Apply Custom Fonts in .NET MAUI How to Apply Custom Fonts in .NET MAUI

A blog about android developement

Adding custom fonts in .NET MAUI (Multi-platform App UI) is a powerful way to improve your app’s design and branding, making it stand out to users across all platforms, including Android, iOS, Windows, and macOS. In this guide, we’ll go through each step required to integrate custom fonts into your .NET MAUI app effectively, helping you achieve a polished, professional look.


Why Use Custom Fonts in .NET MAUI?

Custom fonts provide numerous benefits:

  • Brand Consistency: Reinforce your brand identity by using fonts that align with your style.
  • Improved Readability: Choose fonts that enhance the readability and aesthetics of your app, improving the user experience.
  • Unique Design: Differentiate your app from others by using custom fonts that reflect the purpose and personality of your app.

Adding custom fonts in .NET MAUI is simple and can significantly impact your app's overall design.


Steps to Add Custom Fonts in .NET MAUI

This tutorial breaks down the process into three essential steps:

  1. 1. Add the Font File to Your .NET MAUI Project
  2. 2. Register the Font in MauiProgram.cs
  3. 3. Use the Custom Font in Your XAML or C# Code

Let’s go through each step in detail.


Step 1: Add the Font File to Your .NET MAUI Project

  • Download the Font: Find a .ttf (TrueType Font) or .otf (OpenType Font) file of your desired font.
  • Place the Font in the Correct Folder: Drag and drop the font file into the Resources/Fonts folder in your .NET MAUI project. This step is crucial because .NET MAUI loads custom fonts directly from this folder.
  • Example: If your font file is named MyCustomFont.ttf, place it in Resources/Fonts.

Step 2: Register the Font in MauiProgram.cs

After adding the font file to your project, the next step is to register it in MauiProgram.cs to ensure .NET MAUI recognizes it.

  • Open MauiProgram.cs in your project.
  • Locate the ConfigureFonts Method: Inside the CreateMauiApp method, find ConfigureFonts and add a new line to register your font file. Here’s how it should look:
    builder.ConfigureFonts(fonts =>
    {
        fonts.AddFont("MyCustomFont.ttf", "MyCustomFontAlias");
    });
    
    • "MyCustomFont.ttf" is the font file name located in Resources/Fonts.
    • "MyCustomFontAlias" is the alias name for the font, which you will use to apply the font in XAML or C#.

Step 3: Use the Custom Font in XAML or C#

With the font registered, it’s now ready to use in your UI.


Using the Font in XAML

To apply the custom font to a control in XAML, use the FontFamily property with the alias you created.

<Label Text="Hello, .NET MAUI!"
       FontFamily="MyCustomFontAlias"
       FontSize="24"
       TextColor="Black"/>

Using the Font in C#

If you prefer to set the font programmatically in C#, you can apply it like this:

Label label = new Label
{
    Text = "Hello, .NET MAUI!",
    FontFamily = "MyCustomFontAlias",
    FontSize = 24,
    TextColor = Colors.Black
};

Tips for Successful Font Integration

  • Check File Names: Ensure that the font file name in MauiProgram.cs matches the actual file name, including case sensitivity.
  • Confirm Licensing: Verify the font’s licensing if you’re using it commercially to avoid copyright issues.
  • Compatibility: Test the font across all supported platforms to make sure it appears correctly on Android, iOS, Windows, and macOS.

Benefits of Using Custom Fonts in .NET MAUI

Custom fonts bring a range of benefits:

  • Consistent Appearance: Once set up, the font will appear consistently across all platforms.
  • Enhanced User Experience: A well-chosen font can make your app more user-friendly and visually appealing.
  • Cross-Platform Design: MAUI makes it easy to use custom fonts without additional platform-specific coding, simplifying cross-platform development.

Wrapping Up

Custom fonts can transform the look and feel of your .NET MAUI app, making it more engaging and unique. By following these steps, you’ll be able to easily add and apply custom fonts across all pages in your app. This customization not only enhances user experience but also boosts your app's professionalism and appeal. With .NET MAUI, you can bring your app's design to life with fonts that make an impression! Start experimenting with different fonts and see how they can elevate your app's style.

I'm thrilled to announce that a new version of the QRGenerator plugin has just been released! 🎉 This update brings several enhancement...

🚀 Exciting Update for the QR Generator Plugin! 🚀 🚀 Exciting Update for the QR Generator Plugin! 🚀

A blog about android developement

I'm thrilled to announce that a new version of the QRGenerator plugin has just been released! 🎉


This update brings several enhancements and new features to make your QR code generation even more efficient and user-friendly.


Whether you’re developing for Android or looking to integrate QR code functionality into your applications, this update is designed to streamline your workflow and improve performance.


Key Features
🔹 QR code color can be changed dynamically
🔹 Android X support is included
🔹 Minimum support from version 14 is included
🔹 Margin of the QR code can be controlled

You can explore the full release notes and get the updated version at my QRGenerator GitHub Repository.

A big thank you to the community for your ongoing support and feedback. Your contributions and suggestions help make QRGenerator better with each update.

Feel free to try out the new version and let me know your thoughts or any issues you encounter. Happy coding! 💻✨

Introduction In this tutorial, we will show you how to implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI C...

Detect Long Press in .NET MAUI App using TouchBehavior Detect Long Press in .NET MAUI App using TouchBehavior

A blog about android developement

Introduction

In this tutorial, we will show you how to implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI Community Toolkit. Learn how to trigger long press events or commands with parameters and see a live example of updating a button image on a successful long press.


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

Install Plugin

We need to install the "CommunityToolkit.MAUI" by searching in nuget manager and click "Install" to install the plugin

Implementation

Here, we will add the long press behaviour to the image control and you can use as per your need:

  • Add the below code in the xaml file to have wire-up the event or command between the designer and view model. Add Namespace
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
  • Add the following code in your element. In this example, I used Image control
    <Image.Behaviors>
          <toolkit:TouchBehavior LongPressCommand="LongPressCommand" LongPressDuration="2000" />
    </Image.Behaviors>
  • The event code will be look like the below
    LongPressCommand = new Command(() =>
    {
    	count++;
    
    	if (count == 1)
    		CounterBtn.Text = $"Long pressed {count} time";
    	else
    		CounterBtn.Text = $"Long pressed {count} times";
    
    	SemanticScreenReader.Announce(CounterBtn.Text);
    });

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.

Video Tutorial and Demo:

Introduction This article explores the concept of .NET MAUI handlers and how they are used in development. Handlers act as a bridge bet...

.NET MAUI - Handlers .NET MAUI - Handlers

A blog about android developement

Introduction

This article explores the concept of .NET MAUI handlers and how they are used in development. Handlers act as a bridge between virtual views and native views on each platform. In simpler terms, they are responsible for instantiating the underlying native view and mapping the cross-platform control API to the native view API. This essentially allows developers to use the same code across different platforms without worrying about the underlying implementation details.


Key concepts of handlers include property mappers and command mappers. These mappers define what actions are taken when a property or command changes. Handlers also support lifecycle events that allow developers to perform actions when a handler is created or changed.


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

Here's a simple example for a .NET MAUI Entry handler:

  • Conditional Compilation: #if ANDROID and #endif are conditional compilation directives. They ensure the code within them is only compiled for the Android platform and similar to other platforms as well.
  • Entry Handler Customization:  This code customizes the appearance of Entry controls with the name "BorderlessEntry".
    Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("BorderlessEntry", (handler, view) =>
    {
        if (view is Entry)
        {
            #if ANDROID
            handler.PlatformView.SetBackgroundColor(Microsoft.Maui.Graphics.Colors.Beige.ToAndroid());
            #elif IOS
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
            #elif WINDOWS
            handler.PlatformView.BorderThickness = new Microsoft.UI.Xaml.Thickness(10);
            #endif
        }
    });
    
  • It uses the EntryHandler.Mapper.AppendToMapping method to register a custom mapping for this specific named control.
  • The lambda expression defines what happens when an Entry with the name "BorderlessEntry" is encountered.
  • Inside the lambda, it checks if the view is indeed an Entry control.
  • Then, depending on the platform (Android, iOS, or Windows), it applies platform-specific styling:
    • On Android, the background color is set to beige.
    • On iOS, the border style is removed to create a borderless look.
    • On Windows, a border thickness of 10 is applied.

This code demonstrates how to customize the appearance of an Entry control in .NET MAUI using handlers. By registering a custom mapping for "BorderlessEntry", you can achieve a platform-specific, borderless look for entries with that specific name. This allows for targeted styling without affecting all Entry controls in your app.


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.

Conclusion:

You can customize various other aspects of the Entry control using platform-specific properties and methods within the handler. This approach allows for a more granular control over the appearance of your UI elements on different platforms while maintaining cross-platform compatibility.

Introduction Building a secure .NET MAUI app is essential. Rooted/jailbroken devices bypass security measures, leaving them vulnerable....

.NET MAUI - Root/Jail Broken Detection .NET MAUI - Root/Jail Broken Detection

A blog about android developement

Introduction

Building a secure .NET MAUI app is essential. Rooted/jailbroken devices bypass security measures, leaving them vulnerable. This can impact your app's data and functionality. Let's explore the risks and how to implement root/jailbreak detection in your .NET MAUI app.


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

Install Plugin:

  • Open your Nuget Package Manager and search "banditoth.MAUI.JailbreakDetector" and install the latest version in your project.

Implementation

  • Open MainPage.xaml file and update the UI as per your requirement. In this sample, I have added a button to check whether the device is rooted or not.
  • You can dependency inject the jailbreak detector instance, by resolving an instance of IJailbreakDetector. Store the instance in a private readonly field in your class, or use it directly.
    IJailbreakDetectorConfiguration jailbreakDetectorConfiguration = new JailbreakSettings();
    jailbreakDetectorConfiguration.MaximumPossibilityPercentage = 20;
    jailbreakDetectorConfiguration.MaximumWarningCount = 1;
    jailbreakDetectorConfiguration.CanThrowException = true;
    
    IJailbreakDetector jailbreakDetector = new JailberakDetectorService(jailbreakDetectorConfiguration);
  • Use the following code to check the device is rooted or not.
    if (jailbreakDetector.IsSupported())
    {
    	var isRooted = await jailbreakDetector.IsRootedOrJailbrokenAsync();
    	if (isRooted)
    	{
    		await DisplayAlert("ANDROIDMADS - .NET MAUI", "DEVICE IS ROOTED", "OK");
    	}
    	else
    	{
    		await DisplayAlert("ANDROIDMADS - .NET MAUI", "DEVICE IS NOT ROOTED", "OK");
    	}
    }

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.

Introduction: Building an API in PHP is a fundamental aspect of web development, enabling seamless communication between different s...

Effortlessly Build a PHP API with PHP API Builder - CLI: Step-by-Step Guide Effortlessly Build a PHP API with PHP API Builder - CLI: Step-by-Step Guide

A blog about android developement

Introduction:

Building an API in PHP is a fundamental aspect of web development, enabling seamless communication between different software applications. With the PHP API Builder - CLI tool, creating robust APIs becomes a breeze. This command-line interface simplifies the process by generating PHP files tailored for handling Create, Read, Update, and Delete operations (CRUD) on your specified database tables.


PHP API Builder - CLI streamlines API development by automating repetitive tasks, allowing developers to focus on crafting efficient solutions. Whether you're a seasoned developer or just starting with PHP, this tool offers a user-friendly approach to quickly generate API files with minimal effort.


Now, let's dive into the details of using PHP API Builder - CLI to harness the power of PHP for building APIs.


Requirements:

  • PHP installed on your system.
  • Access to the database you want to generate API files for.

Usage:

  • Run the CLI Tool: Open PhpApiBuilder.exe CLI tool where it is located.
  • Input Hostname: When prompted, enter the hostname of your database server. If it's 'localhost', you can press Enter to proceed with the default value.
  • Input Database Name: Enter the name of the database you want to generate API files for.
  • Input Username: Provide the username to access the specified database.
  • Input Password: If your database requires a password, enter it when prompted. If there's no password, you can press Enter to proceed with an empty password.
  • Enter PHP File Name: Specify the desired name for the PHP file that will be generated. Do not include the ".php" extension.
  • Enter Table Name: Input the name of the table for which you want to generate CRUD operations API.
  • Review Output: Once all the necessary information is provided, the CLI tool will generate the PHP file containing CRUD operations for the specified table. If any errors occur during the process (e.g., invalid credentials, table not found), the CLI will display an error message and prompt you to restart the process from the beginning.
  • Accessing Generated Files: The generated PHP file will be available in the same directory where the CLI tool is located.

Example:

Suppose you want to generate API files for a database named "my_database" with the table "users". Here's how you would use the PHP API Builder - CLI tool:

Enter hostname (default: localhost): localhost
Enter database name: my_database
Enter username: my_username
Enter password (default: empty):
Enter PHP file name (without .php extension): users_api
Enter table name: users

After providing the necessary information, the tool will generate the "users_api.php" file in the tool's directory.


Note:

  • Make sure to review the generated PHP file to ensure it meets your requirements and security standards before using it in your project.
  • It's recommended to back up your database before performing any CRUD operations using the generated API files.
  • For any assistance or issues with the PHP API Builder - CLI tool, refer to the documentation or contact support.

Conclusion:

This manual provides a comprehensive guide for using the PHP API Builder - CLI tool to efficiently generate API files for CRUD operations on your database tables.


Download:

You can download this tool 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.

In the ever-evolving landscape of technology, tools and frameworks continuously evolve, and developers must stay ahead of the curve. One si...

Good Bye Xamarin Good Bye Xamarin

A blog about android developement

In the ever-evolving landscape of technology, tools and frameworks continuously evolve, and developers must stay ahead of the curve. One significant evolution in recent times is the transition from Xamarin.Forms to .NET MAUI (Multi-platform App UI). This shift brings about a series of changes and deadlines that developers must navigate skillfully. In this article, we'll simplify and explore the essential milestones and recommendations to smoothly transition from Xamarin to .NET MAUI.

Saying Farewell to Xamarin

Xamarin.Forms, the precursor to .NET MAUI, is reaching its twilight phase. Existing Xamarin.Forms projects now have the imperative of migrating to .NET MAUI, with Xamarin itself approaching its expiration date. It's vital to note that support for all Xamarin SDKs, including Xamarin.Forms, will come to an end after May 1, 2024.

For those seeking comprehensive insights into this transition, detailed information and guidelines are available in the official documentation.

Navigating the Transition to .NET 7

Complicating matters further is the impending end of support for .NET 7, scheduled for May 14, 2023. To mitigate potential challenges, it's wise to initiate migrations well in advance, allowing ample time to address any arising issues during the process. For detailed information, delve into the resources provided.

Embracing Visual Studio Code

As Visual Studio for Mac faces retirement by August 31, 2024, developers may find themselves at a crossroads. However, there's no cause for concern as the transition to .NET MAUI can seamlessly continue using Visual Studio Code. Learn how to implement the MAUI Extension for Visual Studio Code and access additional resources in the official documentation.

Understanding App Store Transition Deadlines

The transition timeline extends beyond development environments to app distribution platforms. It's anticipated that by April 2025, the Apple App Store will likely stop accepting submissions of Xamarin applications built with Xcode 15. Similarly, the Google Play Store is expected to cease supporting Xamarin apps targeting API 34 by August 2025.

For more information on these transitions, refer to the provided links.

Fostering Community Engagement

In the spirit of community collaboration, developers are encouraged to share their feedback with the Microsoft team through David Ortinau's facilitated platform. Your experiences are invaluable in enriching the community and streamlining the migration process from Xamarin to .NET MAUI. Participate in the feedback survey to contribute to this collective effort.

Showcasing Your .NET MAUI Creations

As .NET MAUI gains momentum, Microsoft eagerly seeks to showcase applications developed using this framework. Your contributions and feedback play a pivotal role in shaping the future of .NET MAUI. Keep an eye out for Microsoft events where .NET MAUI applications are celebrated and showcased.


In conclusion, transitioning from Xamarin to .NET MAUI signifies a significant milestone in the realm of cross-platform app development. By staying informed, proactive, and leveraging available resources, developers can navigate this transition with confidence and agility, propelling their projects into the future.


Certainly! Here's a tabulated overview of the key dates and their details:

Date Event Details
May 1, 2024 End of Xamarin Official Support Support for all Xamarin SDKs, including Xamarin.Forms, will cease after this date.
May 14, 2023 End of .NET 7 Official Support Support for .NET 7 will be terminated, urging developers to plan migration strategies well in advance.
August 31, 2024 Retirement of Visual Studio for Mac Visual Studio for Mac will be retired, prompting developers to transition to alternative environments such as Visual Studio Code.
April 2025 Apple App Store Transition Deadline The anticipated final deadline for the Apple App Store to accept submissions of Xamarin applications built with Xcode 15.
August 2025 Google Play Store Transition Deadline The expected final deadline for the Google Play Store to accept Xamarin apps targeting API 34.

These dates serve as crucial milestones for developers navigating the transition from Xamarin to .NET MAUI. It's essential to stay informed and plan accordingly to ensure a smooth and seamless transition process.

Introduction Imagine building an app that works on different devices like phones and computers using .NET MAUI. Sometimes, it...

.NET MAUI - Base64 Image Encode/Decode .NET MAUI - Base64 Image Encode/Decode

A blog about android developement

Introduction

Imagine building an app that works on different devices like phones and computers using .NET MAUI. Sometimes, it's tricky to show images in your app, especially when they're encoded in Base64. This blog helps you figure out how to do that easily. We'll break down the steps, making it simple for 10th-grade students to follow along. By the end, you'll know how to make your app look cool with Base64 images in .NET MAUI!


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

  • Open MainPage.xaml file and update the UI as per requirement. And below my screen design.
    <?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="MauiBase64Image.MainPage">
    
        <ScrollView>
            <VerticalStackLayout
                Spacing="25"
                Padding="30,0"
                VerticalOptions="Center">
    
                <Label
                    x:Name="base64Result"
                    Text=""
                    MaxLines="5"
                    SemanticProperties.HeadingLevel="Level1"
                    FontSize="12"
                    HorizontalOptions="Center" />
    
                <Button
                    x:Name="EncodeBtn"
                    Text="Base64 Encode"
                    Clicked="OnEncodeClicked"
                    HorizontalOptions="Center" />
    
                <Image
                    x:Name="imagePreview"
                    HeightRequest="200"
                    HorizontalOptions="Center" />
    
                <Button
                    x:Name="DecodeBtn"
                    Text="Base64 Decode"
                    Clicked="OnDecodeClicked"
                    HorizontalOptions="Center" />
    
            </VerticalStackLayout>
        </ScrollView>
    
    </ContentPage>

Base64 String to Image:

If you're into turning one thing into another, the Convert class in .NET is like a superhero! It helps change stuff, even binary files, into this special code called Base64.


Here's a little example code that shows how to use this superhero class to make a special picture show up in a .NET MAUI app. But here's the trick: don't use the word 'using' like we usually do when talking to the computer. If we do that, it might close the door too early before the picture is ready to show.


var imageBytes = Convert.FromBase64String(base64Result.Text);
MemoryStream imageDecodeStream = new(imageBytes);
imagePreview.Source = ImageSource.FromStream(() => imageDecodeStream);

Image to Base64 String:

Now, let's learn how to do the opposite – turning a picture into a base64 string! We use something called Convert.ToBase64String() in .NET MAUI, which is like a tool for this job.


As you might have guessed, the first step is changing our picture into something called a byte array, which is like breaking it into small pieces. In .NET MAUI, you can grab a file from your app (maybe in the Resources\Raw folder) using the FileSystem tools.


using var imageEncodeStream = await FileSystem.OpenAppPackageFileAsync("icon.png");
using var memoryStream = new MemoryStream();

imageEncodeStream.CopyTo(memoryStream);
base64Result.Text = Convert.ToBase64String(memoryStream.ToArray());

Here's how it works: we turn the picture into a Stream, put it in a special memory place called MemoryStream, and then change it into those small pieces, the byte array. Take a look at this code example to see how it's done.


See those 'using' words? They make sure everything is cleaned up nicely when we finish. Remember, there could be different ways to get files, but as long as you can turn your picture into a byte array, you're good to go in your .NET MAUI journey!


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.