Showing posts with label digital signature. Show all posts

.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

digital signature

.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.

In this post, I will show you how to Create Digital Signature in Android. Project Structure: Create a new Project in Eclipse/Android ...

How to Create a Digital Signature Application in Android How to Create a Digital Signature Application in Android

A blog about android developement

digital signature

How to Create a Digital Signature Application in Android
In this post, I will show you how to Create Digital Signature in Android.

Project Structure:

Create a new Project in Eclipse/Android Studio with the required Specifications.

Codes:

AndroidManifest.xml
Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
color.xml
Create color.xml and replace it with the following code
<resources>
    <color name="ColorPrimaryDark">#3367d6</color>
    <color name="ColorPrimary">#4285f4</color>
</resources>
strings.xml
Create strings.xml and replace it with the following code
<resources>
 <string name="app_name">Digital Signature</string>
 <string name="hello_world">Hello world!</string>
 <string name="action_settings">Settings</string>
 <string name="hint_sign">Get Signature</string>
 <string name="dialog_title">SIGN HERE</string>
 <string name="hint_cancel">Cancel</string>
 <string name="hint_clear">Clear</string>
 <string name="hint_save">Save</string>
</resources>
activity_toolbar.xml
Create activity_toolbar.xml and replace it with the following code
<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="wrap_content"
    tools:context="@string/app_name">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/AppTheme"
        app:popupTheme="@style/AppTheme" />

</RelativeLayout>
activity_main.xml
Create activity_main.xml and replace it with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/white">

    <include layout="@layout/activity_toolbar" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:gravity="center">

        <Button
            android:id="@+id/signature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hint_sign"
            android:padding="5dp"
            android:background="@color/ColorPrimary" />
    </LinearLayout>

</LinearLayout>
dialog_signature.xml
Create dialog_signature.xml and replace it with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="400dp"
    android:orientation="vertical"
    android:background="@android:color/white">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/ColorPrimaryDark"
        android:text="@string/dialog_title"
        android:textColor="@android:color/white"
        android:padding="5dp"
        android:gravity="center"/>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:background="@android:color/white">

        <Button
            android:id="@+id/cancel"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_cancel"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

        <Button
            android:id="@+id/clear"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_clear"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

        <Button
            android:id="@+id/getsign"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_save"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical" />

</LinearLayout>
MainActivity.java
Open MainActivity.java and replace it with the following code
package com.example.digitalsignature;
 
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
 
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
 
public class MainActivity extends AppCompatActivity {

 Toolbar toolbar;
 Button btn_get_sign, mClear, mGetSign, mCancel;

 File file;
 Dialog dialog;
 LinearLayout mContent;
 View view;
 signature mSignature;
 Bitmap bitmap;

 // Creating Separate Directory for saving Generated Images
 String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
 String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
 String StoredPath = DIRECTORY + pic_name + ".png";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Setting ToolBar as ActionBar
  toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);

  // Button to open signature panel
  btn_get_sign = (Button) findViewById(R.id.signature);

  // Method to create Directory, if the Directory doesn't exists
  file = new File(DIRECTORY);
  if (!file.exists()) {
   file.mkdir();
  }

  // Dialog Function
  dialog = new Dialog(MainActivity.this);
  // Removing the features of Normal Dialogs
  dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
  dialog.setContentView(R.layout.dialog_signature);
  dialog.setCancelable(true);

  btn_get_sign.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
   // Function call for Digital Signature
    dialog_action();

   }
  });
 }
 // Function for Digital Signature
 public void dialog_action() {
 
  mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
  mSignature = new signature(getApplicationContext(), null);
  mSignature.setBackgroundColor(Color.WHITE);
  // Dynamically generating Layout through java code
  mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
  mClear = (Button) dialog.findViewById(R.id.clear);
  mGetSign = (Button) dialog.findViewById(R.id.getsign);
  mGetSign.setEnabled(false);
  mCancel = (Button) dialog.findViewById(R.id.cancel);
  view = mContent;

  mClear.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    Log.v("tag", "Panel Cleared");
    mSignature.clear();
    mGetSign.setEnabled(false);
   }
  });
  mGetSign.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    Log.v("tag", "Panel Saved");
    view.setDrawingCacheEnabled(true);
    mSignature.save(view, StoredPath);
    dialog.dismiss();
    Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
    // Calling the same class
    recreate();
   }
  });
  mCancel.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    Log.v("tag", "Panel Cancelled");
    dialog.dismiss();
    // Calling the same class
    recreate();
   }
  });
  dialog.show();
 }

 public class signature extends View {
  private static final float STROKE_WIDTH = 5f;
  private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
  private Paint paint = new Paint();
  private Path path = new Path();

  private float lastTouchX;
  private float lastTouchY;
  private final RectF dirtyRect = new RectF();

  public signature(Context context, AttributeSet attrs) {
   super(context, attrs);
   paint.setAntiAlias(true);
   paint.setColor(Color.BLACK);
   paint.setStyle(Paint.Style.STROKE);
   paint.setStrokeJoin(Paint.Join.ROUND);
   paint.setStrokeWidth(STROKE_WIDTH);
  }

  public void save(View v, String StoredPath) {
   Log.v("tag", "Width: " + v.getWidth());
   Log.v("tag", "Height: " + v.getHeight());
   if (bitmap == null) {
    bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
   }
   Canvas canvas = new Canvas(bitmap);
   try {
    // Output the file
    FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
    v.draw(canvas);
    // Convert the output file to Image such as .png
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
    mFileOutStream.flush();
    mFileOutStream.close();
   } catch (Exception e) {
    Log.v("log_tag", e.toString());
   }
  }

  public void clear() {
   path.reset();
   invalidate();
  }

  @Override
  protected void onDraw(Canvas canvas) {
   canvas.drawPath(path, paint);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   float eventX = event.getX();
   float eventY = event.getY();
   mGetSign.setEnabled(true);

   switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     path.moveTo(eventX, eventY);
     lastTouchX = eventX;
     lastTouchY = eventY;
     return true;

    case MotionEvent.ACTION_MOVE:
 
    case MotionEvent.ACTION_UP:
     resetDirtyRect(eventX, eventY);
     int historySize = event.getHistorySize();
     for (int i = 0; i < historySize; i++) {
      float historicalX = event.getHistoricalX(i);
      float historicalY = event.getHistoricalY(i);
      expandDirtyRect(historicalX, historicalY);
      path.lineTo(historicalX, historicalY);
     }
     path.lineTo(eventX, eventY);
     break;
    default:
     debug("Ignored touch event: " + event.toString());
     return false;
   }

   invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
     (int) (dirtyRect.top - HALF_STROKE_WIDTH),
     (int) (dirtyRect.right + HALF_STROKE_WIDTH),
     (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

    lastTouchX = eventX;
    lastTouchY = eventY;

    return true;
  }

  private void debug(String string) {
   Log.v("log_tag", string);
  }

  private void expandDirtyRect(float historicalX, float historicalY) {
   if (historicalX < dirtyRect.left) {
    dirtyRect.left = historicalX;
   } else if (historicalX > dirtyRect.right) {
    dirtyRect.right = historicalX;
   }

   if (historicalY < dirtyRect.top) {
    dirtyRect.top = historicalY;
   } else if (historicalY > dirtyRect.bottom) {
    dirtyRect.bottom = historicalY;
   }
  }

  private void resetDirtyRect(float eventX, float eventY) {
   dirtyRect.left = Math.min(lastTouchX, eventX);
   dirtyRect.right = Math.max(lastTouchX, eventX);
   dirtyRect.top = Math.min(lastTouchY, eventY);
   dirtyRect.bottom = Math.max(lastTouchY, eventY);
  }
 }
}

Screen Shots

Screen 1
Screen 2
Screen 3

Download Full Source Code

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.

Download From Github

Post your doubts and comments in the comments section.