Langsung ke konten utama

How to Create a Digital Signature Application in Android

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.  

Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail