Showing posts with label canvas. Show all posts

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

canvas

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.