├── .gitignore
├── LICENSE
├── README.md
├── SignaturePad-Example
├── build.gradle
├── ic_launcher-web.png
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── github
│ │ └── gcacace
│ │ └── signaturepad
│ │ └── MainActivity.java
│ └── res
│ ├── drawable-hdpi
│ └── ic_launcher.png
│ ├── drawable-mdpi
│ └── ic_launcher.png
│ ├── drawable-xhdpi
│ └── ic_launcher.png
│ ├── drawable-xxhdpi
│ └── ic_launcher.png
│ ├── layout
│ └── activity_main.xml
│ ├── values-sw600dp
│ └── dimens.xml
│ ├── values-sw720dp-land
│ └── dimens.xml
│ └── values
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── header.png
├── settings.gradle
└── signature-pad
├── build.gradle
├── proguard-rules-consumer.pro
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── github
│ └── gcacace
│ └── signaturepad
│ ├── utils
│ ├── Bezier.java
│ ├── ControlTimedPoints.java
│ ├── SignaturePadBindingAdapter.java
│ ├── SvgBuilder.java
│ ├── SvgPathBuilder.java
│ ├── SvgPoint.java
│ └── TimedPoint.java
│ ├── view
│ ├── ViewCompat.java
│ └── ViewTreeObserverCompat.java
│ └── views
│ └── SignaturePad.java
└── res
└── values
└── attrs.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | # Gradle files
2 | .gradle/
3 | build/
4 |
5 | # Local configuration file (sdk path, etc)
6 | local.properties
7 |
8 | # Android Studio generated folders
9 | .navigation/
10 | captures/
11 | .externalNativeBuild
12 |
13 | # IntelliJ project files
14 | *.iml
15 | .idea/
16 |
17 | # Misc
18 | .DS_Store
19 |
20 | # Keystore files
21 | *.jks
22 |
23 | # Release/publishing credentials
24 | bintray.properties
25 | release.properties
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Android Signature Pad
2 | ====================
3 |
4 | Android Signature Pad is an Android library for drawing smooth signatures. It uses variable width Bézier curve interpolation based on [Smoother Signatures](http://corner.squareup.com/2012/07/smoother-signatures.html) post by [Square](https://squareup.com).
5 |
6 | 
7 |
8 | ## Features
9 | * Bézier implementation for a smoother line
10 | * Variable point size based on velocity
11 | * Customizable pen color and size
12 | * Bitmap and SVG support
13 | * Data Binding
14 |
15 | ## Installation
16 |
17 | Latest version of the library can be found on Maven Central.
18 |
19 | ### For Gradle users
20 |
21 | Open your `build.gradle` and make sure that Maven Central repository is declared into `repositories` section:
22 | ```gradle
23 | repositories {
24 | mavenCentral()
25 | }
26 | ```
27 | Then, include the library as dependency:
28 | ```gradle
29 | compile 'com.github.gcacace:signature-pad:1.3.1'
30 | ```
31 |
32 | ### For Maven users
33 |
34 | Add this dependency to your `pom.xml`:
35 | ```xml
36 |
37 | com.github.gcacace
38 | signature-pad
39 | 1.3.1
40 | aar
41 |
42 | ```
43 |
44 | ## Usage
45 |
46 | *Please see the `/SignaturePad-Example` app for a more detailed code example of how to use the library.*
47 |
48 | 1. Add the `SignaturePad` view to the layout you want to show.
49 | ```xml
50 |
58 | ```
59 |
60 | 2. Configure attributes.
61 | * `penMinWidth` - The minimum width of the stroke (default: 3dp).
62 | * `penMaxWidth` - The maximum width of the stroke (default: 7dp).
63 | * `penColor` - The color of the stroke (default: Color.BLACK).
64 | * `velocityFilterWeight` - Weight used to modify new velocity based on the previous velocity (default: 0.9).
65 | * `clearOnDoubleClick` - Double click to clear pad (default: false)
66 |
67 | 3. Configure signature events listener
68 |
69 | An `OnSignedListener` can be set on the view:
70 | ```java
71 |
72 | mSignaturePad = (SignaturePad) findViewById(R.id.signature_pad);
73 | mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
74 |
75 | @Override
76 | public void onStartSigning() {
77 | //Event triggered when the pad is touched
78 | }
79 |
80 | @Override
81 | public void onSigned() {
82 | //Event triggered when the pad is signed
83 | }
84 |
85 | @Override
86 | public void onClear() {
87 | //Event triggered when the pad is cleared
88 | }
89 | });
90 | ```
91 |
92 | 4. Get signature data
93 | * `getSignatureBitmap()` - A signature bitmap with a white background.
94 | * `getTransparentSignatureBitmap()` - A signature bitmap with a transparent background.
95 | * `getSignatureSvg()` - A signature Scalable Vector Graphics document.
96 |
97 | ## Data Binding
98 |
99 | The `SignaturePad` view has custom Data Binding attribute setters for all the listener events:
100 |
101 | ```xml
102 |
111 | ```
112 |
113 | ## Cordova Plugin
114 |
115 | Thanks to [netinhoteixeira](https://github.com/netinhoteixeira/), there is a Cordova plugin using that library.
116 | Please refer to https://github.com/netinhoteixeira/cordova-plugin-signature-view.
117 |
118 | ## NativeScript Plugin
119 | Thanks to [bradmartin](https://github.com/bradmartin), there is a NativeScript plugin.
120 | Please refer to [https://github.com/bradmartin/nativescript-signaturepad](https://github.com/bradmartin/nativescript-signaturepad).
121 |
122 | ## Caveats
123 |
124 | Currently doesn't support screen rotations. Pull requests are welcome!
125 |
126 | ## License
127 |
128 | Copyright 2014-2016 Gianluca Cacace
129 |
130 | Licensed under the Apache License, Version 2.0 (the "License");
131 | you may not use this file except in compliance with the License.
132 | You may obtain a copy of the License at
133 |
134 | http://www.apache.org/licenses/LICENSE-2.0
135 |
136 | Unless required by applicable law or agreed to in writing, software
137 | distributed under the License is distributed on an "AS IS" BASIS,
138 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
139 | See the License for the specific language governing permissions and
140 | limitations under the License.
141 |
--------------------------------------------------------------------------------
/SignaturePad-Example/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
5 |
6 | defaultConfig {
7 | minSdkVersion 14
8 | targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
9 | versionName project.VERSION_NAME
10 | versionCode Integer.parseInt(project.VERSION_CODE)
11 | }
12 |
13 | signingConfigs { release }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation project(":signature-pad")
24 | implementation 'androidx.appcompat:appcompat:1.0.0'
25 | }
26 |
--------------------------------------------------------------------------------
/SignaturePad-Example/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/SignaturePad-Example/ic_launcher-web.png
--------------------------------------------------------------------------------
/SignaturePad-Example/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/java/com/github/gcacace/signaturepad/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.graphics.Bitmap;
8 | import android.graphics.Canvas;
9 | import android.graphics.Color;
10 | import android.net.Uri;
11 | import android.os.Bundle;
12 | import android.os.Environment;
13 | import androidx.annotation.NonNull;
14 | import androidx.core.app.ActivityCompat;
15 | import android.util.Log;
16 | import android.view.View;
17 | import android.widget.Button;
18 | import android.widget.Toast;
19 |
20 | import com.github.gcacace.signaturepad.views.SignaturePad;
21 |
22 | import java.io.File;
23 | import java.io.FileOutputStream;
24 | import java.io.IOException;
25 | import java.io.OutputStream;
26 | import java.io.OutputStreamWriter;
27 |
28 | import it.gcacace.signaturepad.R;
29 |
30 | public class MainActivity extends Activity {
31 |
32 | private static final int REQUEST_EXTERNAL_STORAGE = 1;
33 | private static String[] PERMISSIONS_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
34 | private SignaturePad mSignaturePad;
35 | private Button mClearButton;
36 | private Button mSaveButton;
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | verifyStoragePermissions(this);
42 | setContentView(R.layout.activity_main);
43 |
44 | mSignaturePad = (SignaturePad) findViewById(R.id.signature_pad);
45 | mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
46 | @Override
47 | public void onStartSigning() {
48 | Toast.makeText(MainActivity.this, "OnStartSigning", Toast.LENGTH_SHORT).show();
49 | }
50 |
51 | @Override
52 | public void onSigned() {
53 | mSaveButton.setEnabled(true);
54 | mClearButton.setEnabled(true);
55 | }
56 |
57 | @Override
58 | public void onClear() {
59 | mSaveButton.setEnabled(false);
60 | mClearButton.setEnabled(false);
61 | }
62 | });
63 |
64 | mClearButton = (Button) findViewById(R.id.clear_button);
65 | mSaveButton = (Button) findViewById(R.id.save_button);
66 |
67 | mClearButton.setOnClickListener(new View.OnClickListener() {
68 | @Override
69 | public void onClick(View view) {
70 | mSignaturePad.clear();
71 | }
72 | });
73 |
74 | mSaveButton.setOnClickListener(new View.OnClickListener() {
75 | @Override
76 | public void onClick(View view) {
77 | Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
78 | if (addJpgSignatureToGallery(signatureBitmap)) {
79 | Toast.makeText(MainActivity.this, "Signature saved into the Gallery", Toast.LENGTH_SHORT).show();
80 | } else {
81 | Toast.makeText(MainActivity.this, "Unable to store the signature", Toast.LENGTH_SHORT).show();
82 | }
83 | if (addSvgSignatureToGallery(mSignaturePad.getSignatureSvg())) {
84 | Toast.makeText(MainActivity.this, "SVG Signature saved into the Gallery", Toast.LENGTH_SHORT).show();
85 | } else {
86 | Toast.makeText(MainActivity.this, "Unable to store the SVG signature", Toast.LENGTH_SHORT).show();
87 | }
88 | }
89 | });
90 | }
91 |
92 | @Override
93 | public void onRequestPermissionsResult(int requestCode,
94 | @NonNull String permissions[], @NonNull int[] grantResults) {
95 | switch (requestCode) {
96 | case REQUEST_EXTERNAL_STORAGE: {
97 | // If request is cancelled, the result arrays are empty.
98 | if (grantResults.length <= 0
99 | || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
100 | Toast.makeText(MainActivity.this, "Cannot write images to external storage", Toast.LENGTH_SHORT).show();
101 | }
102 | }
103 | }
104 | }
105 |
106 | public File getAlbumStorageDir(String albumName) {
107 | // Get the directory for the user's public pictures directory.
108 | File file = new File(Environment.getExternalStoragePublicDirectory(
109 | Environment.DIRECTORY_PICTURES), albumName);
110 | if (!file.mkdirs()) {
111 | Log.e("SignaturePad", "Directory not created");
112 | }
113 | return file;
114 | }
115 |
116 | public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
117 | Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
118 | Canvas canvas = new Canvas(newBitmap);
119 | canvas.drawColor(Color.WHITE);
120 | canvas.drawBitmap(bitmap, 0, 0, null);
121 | OutputStream stream = new FileOutputStream(photo);
122 | newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
123 | stream.close();
124 | }
125 |
126 | public boolean addJpgSignatureToGallery(Bitmap signature) {
127 | boolean result = false;
128 | try {
129 | File photo = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.jpg", System.currentTimeMillis()));
130 | saveBitmapToJPG(signature, photo);
131 | scanMediaFile(photo);
132 | result = true;
133 | } catch (IOException e) {
134 | e.printStackTrace();
135 | }
136 | return result;
137 | }
138 |
139 | private void scanMediaFile(File photo) {
140 | Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
141 | Uri contentUri = Uri.fromFile(photo);
142 | mediaScanIntent.setData(contentUri);
143 | MainActivity.this.sendBroadcast(mediaScanIntent);
144 | }
145 |
146 | public boolean addSvgSignatureToGallery(String signatureSvg) {
147 | boolean result = false;
148 | try {
149 | File svgFile = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.svg", System.currentTimeMillis()));
150 | OutputStream stream = new FileOutputStream(svgFile);
151 | OutputStreamWriter writer = new OutputStreamWriter(stream);
152 | writer.write(signatureSvg);
153 | writer.close();
154 | stream.flush();
155 | stream.close();
156 | scanMediaFile(svgFile);
157 | result = true;
158 | } catch (IOException e) {
159 | e.printStackTrace();
160 | }
161 | return result;
162 | }
163 |
164 | /**
165 | * Checks if the app has permission to write to device storage
166 | *
167 | * If the app does not has permission then the user will be prompted to grant permissions
168 | *
169 | * @param activity the activity from which permissions are checked
170 | */
171 | public static void verifyStoragePermissions(Activity activity) {
172 | // Check if we have write permission
173 | int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
174 |
175 | if (permission != PackageManager.PERMISSION_GRANTED) {
176 | // We don't have permission so prompt the user
177 | ActivityCompat.requestPermissions(
178 | activity,
179 | PERMISSIONS_STORAGE,
180 | REQUEST_EXTERNAL_STORAGE
181 | );
182 | }
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/SignaturePad-Example/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/SignaturePad-Example/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/SignaturePad-Example/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/SignaturePad-Example/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
18 |
19 |
25 |
26 |
35 |
36 |
40 |
41 |
42 |
49 |
50 |
57 |
58 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/values-sw600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/values-sw720dp-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 | 128dp
8 |
9 |
10 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 16dp
5 | 16dp
6 |
7 |
8 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | SignaturePad
5 | I agree the terms and conditions.
6 | Clear Pad
7 | Save Signature
8 |
9 |
10 |
--------------------------------------------------------------------------------
/SignaturePad-Example/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | google()
4 | jcenter()
5 | }
6 |
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:3.6.1'
9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
10 | }
11 | }
12 |
13 | plugins {
14 | id 'com.jfrog.bintray' version '1.8.4'
15 | id 'maven-publish'
16 | }
17 |
18 | allprojects {
19 | version = VERSION_NAME
20 | group = GROUP
21 |
22 | repositories {
23 | google()
24 | jcenter()
25 | }
26 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
19 | VERSION_NAME=1.3.1
20 | VERSION_CODE=130
21 | GROUP=com.github.gcacace
22 |
23 | POM_NAME=Signature Pad
24 | POM_ARTIFACT_ID=android-signaturepad
25 | POM_DESCRIPTION=A custom Android View to capture signatures
26 | POM_URL=https://github.com/gcacace/android-signaturepad
27 | POM_SCM_URL=https://github.com/gcacace/android-signaturepad
28 | POM_SCM_CONNECTION=scm:git@github.com:gcacace/android-signaturepad.git
29 | POM_SCM_DEV_CONNECTION=scm:git@github.com:gcacace/android-signaturepad.git
30 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
31 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
32 | POM_LICENCE_DIST=repo
33 | POM_DEVELOPER_ID=gcacace
34 | POM_DEVELOPER_NAME=Gianluca Cacace
35 | POM_DEVELOPER_EMAIL=gianluca.cacace@gmail.com
36 |
37 | ANDROID_BUILD_TARGET_SDK_VERSION=29
38 | ANDROID_BUILD_SDK_VERSION=29
39 |
40 | android.useAndroidX=true
41 | android.enableJetifier=true
42 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Aug 08 11:36:01 SGT 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.2-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/header.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gcacace/android-signaturepad/89d35965ad408bd3b3bfc96aa30cbc51d6dbd863/header.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'signaturepad'
2 |
3 | include ':signature-pad', ':SignaturePad-Example'
4 |
--------------------------------------------------------------------------------
/signature-pad/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'maven-publish'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | Properties properties = new Properties()
6 | final def bintrayPropertiesFile = project.rootProject.file('bintray.properties')
7 | if (bintrayPropertiesFile.exists()) properties.load(bintrayPropertiesFile.newDataInputStream())
8 |
9 | android {
10 | compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
11 |
12 | defaultConfig {
13 | minSdkVersion 14
14 | targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
15 | consumerProguardFiles 'proguard-rules-consumer.pro'
16 | }
17 |
18 | dataBinding {
19 | enabled = true
20 | }
21 | }
22 |
23 | bintray {
24 | user = properties.getProperty("bintray.user")
25 | key = properties.getProperty("bintray.apikey")
26 |
27 | configurations = ['archives']
28 | publications = ['aar']
29 | pkg {
30 | repo = "maven"
31 | name = project.POM_ARTIFACT_ID
32 | desc = project.POM_DESCRIPTION
33 | websiteUrl = project.POM_URL
34 | vcsUrl = project.POM_SCM_URL
35 | licenses = ["Apache-2.0"]
36 | publish = true
37 |
38 | version {
39 | gpg {
40 | sign = true
41 | passphrase = properties.getProperty("bintray.gpg.passphrase")
42 | }
43 | mavenCentralSync {
44 | sync = true
45 | user = properties.getProperty("oss.userToken")
46 | password = properties.getProperty("oss.userTokenValue")
47 | close = '1'
48 | }
49 | }
50 | }
51 | }
52 |
53 | project.ext {
54 | mavDevelopers = ["Fe": "Federico"]
55 | mavSiteUrl = "https://github.com/sky-uk/gradle-maven-plugin"
56 | mavGitUrl = mavSiteUrl + '.git'
57 | mavProjectName = 'GradleMavenizer'
58 | mavPublishToInternalRepo = true
59 | mavRepoInternalUrl = "path/to/internal/repo"
60 | mavLibraryLicenses = ["Apache-2.0": 'http://www.apache.org/licenses/LICENSE-2.0.txt']
61 | mavLibraryDescription = "A simple description of the project"
62 | }
63 |
64 | publishing {
65 | publications {
66 | aar(MavenPublication) {
67 | pom {
68 | packaging = 'aar'
69 | name = project.POM_NAME
70 | description = project.POM_DESCRIPTION
71 | url = project.POM_URL
72 | licenses {
73 | license {
74 | name = project.POM_LICENCE_NAME
75 | url = project.POM_LICENCE_URL
76 | }
77 | }
78 | developers {
79 | developer {
80 | id = project.POM_DEVELOPER_ID
81 | name = project.POM_DEVELOPER_NAME
82 | email = project.POM_DEVELOPER_EMAIL
83 | }
84 | }
85 | scm {
86 | connection = project.POM_SCM_URL
87 | developerConnection = project.POM_SCM_CONNECTION
88 | url = project.POM_URL
89 | }
90 | }
91 | }
92 | }
93 | }
94 |
95 | task sourcesJar(type: Jar) {
96 | archiveClassifier.set('sources')
97 | from android.sourceSets.main.java.srcDirs
98 | }
99 |
100 | task javadoc(type: Javadoc) {
101 | source = android.sourceSets.main.java.srcDirs
102 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
103 | }
104 |
105 | task javadocJar(type: Jar, dependsOn: javadoc) {
106 | archiveClassifier.set('javadoc')
107 | from javadoc.destinationDir
108 | }
109 |
110 | artifacts {
111 | archives javadocJar
112 | archives sourcesJar
113 | }
114 |
--------------------------------------------------------------------------------
/signature-pad/proguard-rules-consumer.pro:
--------------------------------------------------------------------------------
1 | -dontwarn android.databinding.**
2 | -keep class android.databinding.** { *; }
3 |
--------------------------------------------------------------------------------
/signature-pad/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/signature-pad/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/Bezier.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | public class Bezier {
4 |
5 | public TimedPoint startPoint;
6 | public TimedPoint control1;
7 | public TimedPoint control2;
8 | public TimedPoint endPoint;
9 |
10 | public Bezier set(TimedPoint startPoint, TimedPoint control1,
11 | TimedPoint control2, TimedPoint endPoint) {
12 | this.startPoint = startPoint;
13 | this.control1 = control1;
14 | this.control2 = control2;
15 | this.endPoint = endPoint;
16 | return this;
17 | }
18 |
19 | public float length() {
20 | int steps = 10;
21 | float length = 0;
22 | double cx, cy, px = 0, py = 0, xDiff, yDiff;
23 |
24 | for (int i = 0; i <= steps; i++) {
25 | float t = (float) i / steps;
26 | cx = point(t, this.startPoint.x, this.control1.x,
27 | this.control2.x, this.endPoint.x);
28 | cy = point(t, this.startPoint.y, this.control1.y,
29 | this.control2.y, this.endPoint.y);
30 | if (i > 0) {
31 | xDiff = cx - px;
32 | yDiff = cy - py;
33 | length += Math.sqrt(xDiff * xDiff + yDiff * yDiff);
34 | }
35 | px = cx;
36 | py = cy;
37 | }
38 | return length;
39 |
40 | }
41 |
42 | public double point(float t, float start, float c1, float c2, float end) {
43 | return start * (1.0 - t) * (1.0 - t) * (1.0 - t)
44 | + 3.0 * c1 * (1.0 - t) * (1.0 - t) * t
45 | + 3.0 * c2 * (1.0 - t) * t * t
46 | + end * t * t * t;
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/ControlTimedPoints.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | /**
4 | * Created by gcacace on 28/02/14.
5 | */
6 | public class ControlTimedPoints {
7 |
8 | public TimedPoint c1;
9 | public TimedPoint c2;
10 |
11 | public ControlTimedPoints set(TimedPoint c1, TimedPoint c2) {
12 | this.c1 = c1;
13 | this.c2 = c2;
14 | return this;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/SignaturePadBindingAdapter.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | import androidx.databinding.BindingAdapter;
4 |
5 | import com.github.gcacace.signaturepad.views.SignaturePad;
6 |
7 | public final class SignaturePadBindingAdapter {
8 |
9 | @BindingAdapter("onStartSigning")
10 | public static void setOnSignedListener(SignaturePad view, final OnStartSigningListener onStartSigningListener) {
11 | setOnSignedListener(view, onStartSigningListener, null, null);
12 | }
13 |
14 | @BindingAdapter("onSigned")
15 | public static void setOnSignedListener(SignaturePad view, final OnSignedListener onSignedListener) {
16 | setOnSignedListener(view, null, onSignedListener, null);
17 | }
18 |
19 | @BindingAdapter("onClear")
20 | public static void setOnSignedListener(SignaturePad view, final OnClearListener onClearListener) {
21 | setOnSignedListener(view, null, null, onClearListener);
22 | }
23 |
24 | @BindingAdapter(value = {"onStartSigning", "onSigned", "onClear"}, requireAll = false)
25 | public static void setOnSignedListener(SignaturePad view, final OnStartSigningListener onStartSigningListener, final OnSignedListener onSignedListener, final OnClearListener onClearListener) {
26 | view.setOnSignedListener(new SignaturePad.OnSignedListener() {
27 | @Override
28 | public void onStartSigning() {
29 | if (onStartSigningListener != null) {
30 | onStartSigningListener.onStartSigning();
31 | }
32 | }
33 |
34 | @Override
35 | public void onSigned() {
36 | if (onSignedListener != null) {
37 | onSignedListener.onSigned();
38 | }
39 | }
40 |
41 | @Override
42 | public void onClear() {
43 | if (onClearListener != null) {
44 | onClearListener.onClear();
45 | }
46 | }
47 | });
48 | }
49 |
50 | public interface OnStartSigningListener {
51 | void onStartSigning();
52 | }
53 |
54 | public interface OnSignedListener {
55 | void onSigned();
56 | }
57 |
58 | public interface OnClearListener {
59 | void onClear();
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/SvgBuilder.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | public class SvgBuilder {
4 |
5 | private final StringBuilder mSvgPathsBuilder = new StringBuilder();
6 | private SvgPathBuilder mCurrentPathBuilder = null;
7 |
8 | public SvgBuilder() {
9 | }
10 |
11 | public void clear() {
12 | mSvgPathsBuilder.setLength(0);
13 | mCurrentPathBuilder = null;
14 | }
15 |
16 | public String build(final int width, final int height) {
17 | if (isPathStarted()) {
18 | appendCurrentPath();
19 | }
20 | return (new StringBuilder())
21 | .append("\n")
22 | .append("")
47 | .toString();
48 | }
49 |
50 | public SvgBuilder append(final Bezier curve, final float strokeWidth) {
51 | final Integer roundedStrokeWidth = Math.round(strokeWidth);
52 | final SvgPoint curveStartSvgPoint = new SvgPoint(curve.startPoint);
53 | final SvgPoint curveControlSvgPoint1 = new SvgPoint(curve.control1);
54 | final SvgPoint curveControlSvgPoint2 = new SvgPoint(curve.control2);
55 | final SvgPoint curveEndSvgPoint = new SvgPoint(curve.endPoint);
56 |
57 | if (!isPathStarted()) {
58 | startNewPath(roundedStrokeWidth, curveStartSvgPoint);
59 | }
60 |
61 | if (!curveStartSvgPoint.equals(mCurrentPathBuilder.getLastPoint())
62 | || !roundedStrokeWidth.equals(mCurrentPathBuilder.getStrokeWidth())) {
63 | appendCurrentPath();
64 | startNewPath(roundedStrokeWidth, curveStartSvgPoint);
65 | }
66 |
67 | mCurrentPathBuilder.append(curveControlSvgPoint1, curveControlSvgPoint2, curveEndSvgPoint);
68 | return this;
69 | }
70 |
71 | private void startNewPath(Integer roundedStrokeWidth, SvgPoint curveStartSvgPoint) {
72 | mCurrentPathBuilder = new SvgPathBuilder(curveStartSvgPoint, roundedStrokeWidth);
73 | }
74 |
75 | private void appendCurrentPath() {
76 | mSvgPathsBuilder.append(mCurrentPathBuilder);
77 | }
78 |
79 | private boolean isPathStarted() {
80 | return mCurrentPathBuilder != null;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/SvgPathBuilder.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 |
4 | /**
5 | * Build a SVG path as a string.
6 | *
7 | * https://www.w3.org/TR/SVGTiny12/paths.html
8 | */
9 | public class SvgPathBuilder {
10 |
11 | public static final Character SVG_RELATIVE_CUBIC_BEZIER_CURVE = 'c';
12 | public static final Character SVG_MOVE = 'M';
13 | private final StringBuilder mStringBuilder;
14 | private final Integer mStrokeWidth;
15 | private final SvgPoint mStartPoint;
16 | private SvgPoint mLastPoint;
17 |
18 | public SvgPathBuilder(final SvgPoint startPoint, final Integer strokeWidth) {
19 | mStrokeWidth = strokeWidth;
20 | mStartPoint = startPoint;
21 | mLastPoint = startPoint;
22 | mStringBuilder = new StringBuilder();
23 | mStringBuilder.append(SVG_RELATIVE_CUBIC_BEZIER_CURVE);
24 | }
25 |
26 | public final Integer getStrokeWidth() {
27 | return mStrokeWidth;
28 | }
29 |
30 | public final SvgPoint getLastPoint() {
31 | return mLastPoint;
32 | }
33 |
34 | public SvgPathBuilder append(final SvgPoint controlPoint1, final SvgPoint controlPoint2, final SvgPoint endPoint) {
35 | mStringBuilder.append(makeRelativeCubicBezierCurve(controlPoint1, controlPoint2, endPoint));
36 | mLastPoint = endPoint;
37 | return this;
38 | }
39 |
40 | @Override
41 | public String toString() {
42 | return (new StringBuilder())
43 | .append("")
52 | .toString();
53 | }
54 |
55 | private String makeRelativeCubicBezierCurve(final SvgPoint controlPoint1, final SvgPoint controlPoint2, final SvgPoint endPoint) {
56 | final String sControlPoint1 = controlPoint1.toRelativeCoordinates(mLastPoint);
57 | final String sControlPoint2 = controlPoint2.toRelativeCoordinates(mLastPoint);
58 | final String sEndPoint = endPoint.toRelativeCoordinates(mLastPoint);
59 |
60 | final StringBuilder sb = new StringBuilder();
61 | sb.append(sControlPoint1);
62 | sb.append(" ");
63 | sb.append(sControlPoint2);
64 | sb.append(" ");
65 | sb.append(sEndPoint);
66 | sb.append(" ");
67 |
68 | // discard zero curve
69 | final String svg = sb.toString();
70 | if ("c0 0 0 0 0 0".equals(svg)) {
71 | return "";
72 | } else {
73 | return svg;
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/SvgPoint.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | /**
4 | * Represent a point as it would be in the generated SVG document.
5 | */
6 | class SvgPoint {
7 |
8 | final Integer x, y;
9 |
10 | public SvgPoint(TimedPoint point) {
11 | // one optimisation is to get rid of decimals as they are mostly non-significant in the
12 | // produced SVG image
13 | x = Math.round(point.x);
14 | y = Math.round(point.y);
15 | }
16 |
17 | public SvgPoint(int x, int y) {
18 | this.x = x;
19 | this.y = y;
20 | }
21 |
22 | public String toAbsoluteCoordinates() {
23 | StringBuilder stringBuilder = new StringBuilder();
24 | stringBuilder.append(x);
25 | stringBuilder.append(",");
26 | stringBuilder.append(y);
27 | return stringBuilder.toString();
28 | }
29 |
30 | public String toRelativeCoordinates(final SvgPoint referencePoint) {
31 | return (new SvgPoint(x - referencePoint.x, y - referencePoint.y)).toString();
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | return toAbsoluteCoordinates();
37 | }
38 |
39 | @Override
40 | public boolean equals(Object o) {
41 | if (this == o) return true;
42 | if (o == null || getClass() != o.getClass()) return false;
43 |
44 | SvgPoint svgPoint = (SvgPoint) o;
45 |
46 | if (!x.equals(svgPoint.x)) return false;
47 | return y.equals(svgPoint.y);
48 |
49 | }
50 |
51 | @Override
52 | public int hashCode() {
53 | int result = x.hashCode();
54 | result = 31 * result + y.hashCode();
55 | return result;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/utils/TimedPoint.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.utils;
2 |
3 | public class TimedPoint {
4 | public float x;
5 | public float y;
6 | public long timestamp;
7 |
8 | public TimedPoint set(float x, float y) {
9 | this.x = x;
10 | this.y = y;
11 | this.timestamp = System.currentTimeMillis();
12 | return this;
13 | }
14 |
15 | public float velocityFrom(TimedPoint start) {
16 | long diff = this.timestamp - start.timestamp;
17 | if(diff <= 0) {
18 | diff = 1;
19 | }
20 | float velocity = distanceTo(start) / diff;
21 | if (Float.isInfinite(velocity) || Float.isNaN(velocity)) {
22 | velocity = 0;
23 | }
24 | return velocity;
25 | }
26 |
27 | public float distanceTo(TimedPoint point) {
28 | return (float) Math.sqrt(Math.pow(point.x - this.x, 2) + Math.pow(point.y - this.y, 2));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/view/ViewCompat.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.view;
2 |
3 | import android.os.Build;
4 | import android.view.View;
5 |
6 | public class ViewCompat {
7 | /**
8 | * Returns true if {@code view} has been through at least one layout since it
9 | * was last attached to or detached from a window.
10 | *
11 | * See http://developer.android.com/reference/android/support/v4/view/ViewCompat.html#isLaidOut%28android.view.View%29
12 | *
13 | * @param view the view
14 | * @return true if this view has been through at least one layout since it was last attached to or detached from a window.
15 | */
16 | public static boolean isLaidOut(View view) {
17 | // Future (API19+)...
18 | if (Build.VERSION.SDK_INT >= 19) {
19 | return view.isLaidOut();
20 | }
21 | // Legacy...
22 | return view.getWidth() > 0 && view.getHeight() > 0;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/view/ViewTreeObserverCompat.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.view;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Build;
5 | import android.view.ViewTreeObserver;
6 |
7 | public class ViewTreeObserverCompat {
8 | /**
9 | * Remove a previously installed global layout callback.
10 | * @param observer the view observer
11 | * @param victim the victim
12 | */
13 | @SuppressLint("NewApi")
14 | @SuppressWarnings("deprecation")
15 | public static void removeOnGlobalLayoutListener(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener victim) {
16 | // Future (API16+)...
17 | if (Build.VERSION.SDK_INT >= 16) {
18 | observer.removeOnGlobalLayoutListener(victim);
19 | }
20 | // Legacy...
21 | else {
22 | observer.removeGlobalOnLayoutListener(victim);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/signature-pad/src/main/java/com/github/gcacace/signaturepad/views/SignaturePad.java:
--------------------------------------------------------------------------------
1 | package com.github.gcacace.signaturepad.views;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Bitmap;
7 | import android.graphics.Canvas;
8 | import android.graphics.Color;
9 | import android.graphics.Matrix;
10 | import android.graphics.Paint;
11 | import android.graphics.RectF;
12 | import android.os.Bundle;
13 | import android.os.Parcelable;
14 | import android.util.AttributeSet;
15 | import android.util.Log;
16 | import android.view.GestureDetector;
17 | import android.view.MotionEvent;
18 | import android.view.View;
19 | import android.view.ViewTreeObserver;
20 |
21 | import com.github.gcacace.signaturepad.R;
22 | import com.github.gcacace.signaturepad.utils.Bezier;
23 | import com.github.gcacace.signaturepad.utils.ControlTimedPoints;
24 | import com.github.gcacace.signaturepad.utils.SvgBuilder;
25 | import com.github.gcacace.signaturepad.utils.TimedPoint;
26 | import com.github.gcacace.signaturepad.view.ViewCompat;
27 | import com.github.gcacace.signaturepad.view.ViewTreeObserverCompat;
28 |
29 | import java.util.ArrayList;
30 | import java.util.List;
31 |
32 | public class SignaturePad extends View {
33 | private static final String TAG = SignaturePad.class.getName();
34 |
35 | //View state
36 | private List mPoints;
37 | private boolean mIsEmpty;
38 | private Boolean mHasEditState;
39 | private float mLastTouchX;
40 | private float mLastTouchY;
41 | private float mLastVelocity;
42 | private float mLastWidth;
43 | private RectF mDirtyRect;
44 | private Bitmap mBitmapSavedState;
45 |
46 | private final SvgBuilder mSvgBuilder = new SvgBuilder();
47 |
48 | // Cache
49 | private List mPointsCache = new ArrayList<>();
50 | private ControlTimedPoints mControlTimedPointsCached = new ControlTimedPoints();
51 | private Bezier mBezierCached = new Bezier();
52 |
53 | //Configurable parameters
54 | private int mMinWidth;
55 | private int mMaxWidth;
56 | private float mVelocityFilterWeight;
57 | private OnSignedListener mOnSignedListener;
58 | private boolean mClearOnDoubleClick;
59 |
60 | //Double click detector
61 | private GestureDetector mGestureDetector;
62 |
63 | //Default attribute values
64 | private final int DEFAULT_ATTR_PEN_MIN_WIDTH_PX = 3;
65 | private final int DEFAULT_ATTR_PEN_MAX_WIDTH_PX = 7;
66 | private final int DEFAULT_ATTR_PEN_COLOR = Color.BLACK;
67 | private final float DEFAULT_ATTR_VELOCITY_FILTER_WEIGHT = 0.9f;
68 | private final boolean DEFAULT_ATTR_CLEAR_ON_DOUBLE_CLICK = false;
69 |
70 | private Paint mPaint = new Paint();
71 | private Bitmap mSignatureBitmap = null;
72 | private Canvas mSignatureBitmapCanvas = null;
73 |
74 | public SignaturePad(Context context, AttributeSet attrs) {
75 | super(context, attrs);
76 |
77 | TypedArray a = context.getTheme().obtainStyledAttributes(
78 | attrs,
79 | R.styleable.SignaturePad,
80 | 0, 0);
81 |
82 | //Configurable parameters
83 | try {
84 | mMinWidth = a.getDimensionPixelSize(R.styleable.SignaturePad_penMinWidth, convertDpToPx(DEFAULT_ATTR_PEN_MIN_WIDTH_PX));
85 | mMaxWidth = a.getDimensionPixelSize(R.styleable.SignaturePad_penMaxWidth, convertDpToPx(DEFAULT_ATTR_PEN_MAX_WIDTH_PX));
86 | mPaint.setColor(a.getColor(R.styleable.SignaturePad_penColor, DEFAULT_ATTR_PEN_COLOR));
87 | mVelocityFilterWeight = a.getFloat(R.styleable.SignaturePad_velocityFilterWeight, DEFAULT_ATTR_VELOCITY_FILTER_WEIGHT);
88 | mClearOnDoubleClick = a.getBoolean(R.styleable.SignaturePad_clearOnDoubleClick, DEFAULT_ATTR_CLEAR_ON_DOUBLE_CLICK);
89 | } finally {
90 | a.recycle();
91 | }
92 |
93 | //Fixed parameters
94 | mPaint.setAntiAlias(true);
95 | mPaint.setStyle(Paint.Style.STROKE);
96 | mPaint.setStrokeCap(Paint.Cap.ROUND);
97 | mPaint.setStrokeJoin(Paint.Join.ROUND);
98 |
99 | //Dirty rectangle to update only the changed portion of the view
100 | mDirtyRect = new RectF();
101 |
102 | clearView();
103 |
104 | mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
105 | @Override
106 | public boolean onDoubleTap(MotionEvent e) {
107 | return onDoubleClick();
108 | }
109 | });
110 | }
111 |
112 | @Override
113 | protected Parcelable onSaveInstanceState() {
114 | try {
115 | Bundle bundle = new Bundle();
116 | bundle.putParcelable("superState", super.onSaveInstanceState());
117 | if (this.mHasEditState == null || this.mHasEditState) {
118 | this.mBitmapSavedState = this.getTransparentSignatureBitmap();
119 | }
120 | bundle.putParcelable("signatureBitmap", this.mBitmapSavedState);
121 | return bundle;
122 | } catch(Exception e) {
123 | Log.w(TAG, String.format("error saving instance state: %s", e.getMessage()));
124 | return super.onSaveInstanceState();
125 | }
126 | }
127 |
128 | @Override
129 | protected void onRestoreInstanceState(Parcelable state) {
130 | if (state instanceof Bundle) {
131 | Bundle bundle = (Bundle) state;
132 | this.setSignatureBitmap((Bitmap) bundle.getParcelable("signatureBitmap"));
133 | this.mBitmapSavedState = bundle.getParcelable("signatureBitmap");
134 | state = bundle.getParcelable("superState");
135 | }
136 | this.mHasEditState = false;
137 | super.onRestoreInstanceState(state);
138 | }
139 |
140 | /**
141 | * Set the pen color from a given resource.
142 | * If the resource is not found, {@link android.graphics.Color#BLACK} is assumed.
143 | *
144 | * @param colorRes the color resource.
145 | */
146 | public void setPenColorRes(int colorRes) {
147 | try {
148 | setPenColor(getResources().getColor(colorRes));
149 | } catch (Resources.NotFoundException ex) {
150 | setPenColor(Color.parseColor("#000000"));
151 | }
152 | }
153 |
154 | /**
155 | * Set the pen color from a given color.
156 | *
157 | * @param color the color.
158 | */
159 | public void setPenColor(int color) {
160 | mPaint.setColor(color);
161 | }
162 |
163 | /**
164 | * Set the minimum width of the stroke in pixel.
165 | *
166 | * @param minWidth the width in dp.
167 | */
168 | public void setMinWidth(float minWidth) {
169 | mMinWidth = convertDpToPx(minWidth);
170 | mLastWidth = (mMinWidth + mMaxWidth) / 2f;
171 | }
172 |
173 | /**
174 | * Set the maximum width of the stroke in pixel.
175 | *
176 | * @param maxWidth the width in dp.
177 | */
178 | public void setMaxWidth(float maxWidth) {
179 | mMaxWidth = convertDpToPx(maxWidth);
180 | mLastWidth = (mMinWidth + mMaxWidth) / 2f;
181 | }
182 |
183 | /**
184 | * Set the velocity filter weight.
185 | *
186 | * @param velocityFilterWeight the weight.
187 | */
188 | public void setVelocityFilterWeight(float velocityFilterWeight) {
189 | mVelocityFilterWeight = velocityFilterWeight;
190 | }
191 |
192 | public void clearView() {
193 | mSvgBuilder.clear();
194 | mPoints = new ArrayList<>();
195 | mLastVelocity = 0;
196 | mLastWidth = (mMinWidth + mMaxWidth) / 2f;
197 |
198 | if (mSignatureBitmap != null) {
199 | mSignatureBitmap = null;
200 | ensureSignatureBitmap();
201 | }
202 |
203 | setIsEmpty(true);
204 |
205 | invalidate();
206 | }
207 |
208 | public void clear() {
209 | this.clearView();
210 | this.mHasEditState = true;
211 | }
212 |
213 | @Override
214 | public boolean onTouchEvent(MotionEvent event) {
215 | if (!isEnabled())
216 | return false;
217 |
218 | float eventX = event.getX();
219 | float eventY = event.getY();
220 |
221 | switch (event.getAction()) {
222 | case MotionEvent.ACTION_DOWN:
223 | getParent().requestDisallowInterceptTouchEvent(true);
224 | mPoints.clear();
225 | if (mGestureDetector.onTouchEvent(event)) break;
226 | mLastTouchX = eventX;
227 | mLastTouchY = eventY;
228 | addPoint(getNewPoint(eventX, eventY));
229 | if (mOnSignedListener != null) mOnSignedListener.onStartSigning();
230 |
231 | case MotionEvent.ACTION_MOVE:
232 | resetDirtyRect(eventX, eventY);
233 | addPoint(getNewPoint(eventX, eventY));
234 | setIsEmpty(false);
235 | break;
236 |
237 | case MotionEvent.ACTION_UP:
238 | resetDirtyRect(eventX, eventY);
239 | addPoint(getNewPoint(eventX, eventY));
240 | getParent().requestDisallowInterceptTouchEvent(true);
241 | break;
242 |
243 | default:
244 | return false;
245 | }
246 |
247 | //invalidate();
248 | invalidate(
249 | (int) (mDirtyRect.left - mMaxWidth),
250 | (int) (mDirtyRect.top - mMaxWidth),
251 | (int) (mDirtyRect.right + mMaxWidth),
252 | (int) (mDirtyRect.bottom + mMaxWidth));
253 |
254 | return true;
255 | }
256 |
257 | @Override
258 | protected void onDraw(Canvas canvas) {
259 | if (mSignatureBitmap != null) {
260 | canvas.drawBitmap(mSignatureBitmap, 0, 0, mPaint);
261 | }
262 | }
263 |
264 | public void setOnSignedListener(OnSignedListener listener) {
265 | mOnSignedListener = listener;
266 | }
267 |
268 | public boolean isEmpty() {
269 | return mIsEmpty;
270 | }
271 |
272 | public String getSignatureSvg() {
273 | int width = getTransparentSignatureBitmap().getWidth();
274 | int height = getTransparentSignatureBitmap().getHeight();
275 | return mSvgBuilder.build(width, height);
276 | }
277 |
278 | public Bitmap getSignatureBitmap() {
279 | Bitmap originalBitmap = getTransparentSignatureBitmap();
280 | Bitmap whiteBgBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
281 | Canvas canvas = new Canvas(whiteBgBitmap);
282 | canvas.drawColor(Color.WHITE);
283 | canvas.drawBitmap(originalBitmap, 0, 0, null);
284 | return whiteBgBitmap;
285 | }
286 |
287 | public void setSignatureBitmap(final Bitmap signature) {
288 | // View was laid out...
289 | if (ViewCompat.isLaidOut(this)) {
290 | clearView();
291 | ensureSignatureBitmap();
292 |
293 | RectF tempSrc = new RectF();
294 | RectF tempDst = new RectF();
295 |
296 | int dWidth = signature.getWidth();
297 | int dHeight = signature.getHeight();
298 | int vWidth = getWidth();
299 | int vHeight = getHeight();
300 |
301 | // Generate the required transform.
302 | tempSrc.set(0, 0, dWidth, dHeight);
303 | tempDst.set(0, 0, vWidth, vHeight);
304 |
305 | Matrix drawMatrix = new Matrix();
306 | drawMatrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);
307 |
308 | Canvas canvas = new Canvas(mSignatureBitmap);
309 | canvas.drawBitmap(signature, drawMatrix, null);
310 | setIsEmpty(false);
311 | invalidate();
312 | }
313 | // View not laid out yet e.g. called from onCreate(), onRestoreInstanceState()...
314 | else {
315 | getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
316 | @Override
317 | public void onGlobalLayout() {
318 | // Remove layout listener...
319 | ViewTreeObserverCompat.removeOnGlobalLayoutListener(getViewTreeObserver(), this);
320 |
321 | // Signature bitmap...
322 | setSignatureBitmap(signature);
323 | }
324 | });
325 | }
326 | }
327 |
328 | public Bitmap getTransparentSignatureBitmap() {
329 | ensureSignatureBitmap();
330 | return mSignatureBitmap;
331 | }
332 |
333 | public Bitmap getTransparentSignatureBitmap(boolean trimBlankSpace) {
334 |
335 | if (!trimBlankSpace) {
336 | return getTransparentSignatureBitmap();
337 | }
338 |
339 | ensureSignatureBitmap();
340 |
341 | int imgHeight = mSignatureBitmap.getHeight();
342 | int imgWidth = mSignatureBitmap.getWidth();
343 |
344 | int backgroundColor = Color.TRANSPARENT;
345 |
346 | int xMin = Integer.MAX_VALUE,
347 | xMax = Integer.MIN_VALUE,
348 | yMin = Integer.MAX_VALUE,
349 | yMax = Integer.MIN_VALUE;
350 |
351 | boolean foundPixel = false;
352 |
353 | // Find xMin
354 | for (int x = 0; x < imgWidth; x++) {
355 | boolean stop = false;
356 | for (int y = 0; y < imgHeight; y++) {
357 | if (mSignatureBitmap.getPixel(x, y) != backgroundColor) {
358 | xMin = x;
359 | stop = true;
360 | foundPixel = true;
361 | break;
362 | }
363 | }
364 | if (stop)
365 | break;
366 | }
367 |
368 | // Image is empty...
369 | if (!foundPixel)
370 | return null;
371 |
372 | // Find yMin
373 | for (int y = 0; y < imgHeight; y++) {
374 | boolean stop = false;
375 | for (int x = xMin; x < imgWidth; x++) {
376 | if (mSignatureBitmap.getPixel(x, y) != backgroundColor) {
377 | yMin = y;
378 | stop = true;
379 | break;
380 | }
381 | }
382 | if (stop)
383 | break;
384 | }
385 |
386 | // Find xMax
387 | for (int x = imgWidth - 1; x >= xMin; x--) {
388 | boolean stop = false;
389 | for (int y = yMin; y < imgHeight; y++) {
390 | if (mSignatureBitmap.getPixel(x, y) != backgroundColor) {
391 | xMax = x;
392 | stop = true;
393 | break;
394 | }
395 | }
396 | if (stop)
397 | break;
398 | }
399 |
400 | // Find yMax
401 | for (int y = imgHeight - 1; y >= yMin; y--) {
402 | boolean stop = false;
403 | for (int x = xMin; x <= xMax; x++) {
404 | if (mSignatureBitmap.getPixel(x, y) != backgroundColor) {
405 | yMax = y;
406 | stop = true;
407 | break;
408 | }
409 | }
410 | if (stop)
411 | break;
412 | }
413 |
414 | return Bitmap.createBitmap(mSignatureBitmap, xMin, yMin, xMax - xMin, yMax - yMin);
415 | }
416 |
417 | private boolean onDoubleClick() {
418 | if (mClearOnDoubleClick) {
419 | this.clearView();
420 | return true;
421 | }
422 | return false;
423 | }
424 |
425 | private TimedPoint getNewPoint(float x, float y) {
426 | int mCacheSize = mPointsCache.size();
427 | TimedPoint timedPoint;
428 | if (mCacheSize == 0) {
429 | // Cache is empty, create a new point
430 | timedPoint = new TimedPoint();
431 | } else {
432 | // Get point from cache
433 | timedPoint = mPointsCache.remove(mCacheSize - 1);
434 | }
435 |
436 | return timedPoint.set(x, y);
437 | }
438 |
439 | private void recyclePoint(TimedPoint point) {
440 | mPointsCache.add(point);
441 | }
442 |
443 | private void addPoint(TimedPoint newPoint) {
444 | mPoints.add(newPoint);
445 |
446 | int pointsCount = mPoints.size();
447 | if (pointsCount > 3) {
448 |
449 | ControlTimedPoints tmp = calculateCurveControlPoints(mPoints.get(0), mPoints.get(1), mPoints.get(2));
450 | TimedPoint c2 = tmp.c2;
451 | recyclePoint(tmp.c1);
452 |
453 | tmp = calculateCurveControlPoints(mPoints.get(1), mPoints.get(2), mPoints.get(3));
454 | TimedPoint c3 = tmp.c1;
455 | recyclePoint(tmp.c2);
456 |
457 | Bezier curve = mBezierCached.set(mPoints.get(1), c2, c3, mPoints.get(2));
458 |
459 | TimedPoint startPoint = curve.startPoint;
460 | TimedPoint endPoint = curve.endPoint;
461 |
462 | float velocity = endPoint.velocityFrom(startPoint);
463 | velocity = Float.isNaN(velocity) ? 0.0f : velocity;
464 |
465 | velocity = mVelocityFilterWeight * velocity
466 | + (1 - mVelocityFilterWeight) * mLastVelocity;
467 |
468 | // The new width is a function of the velocity. Higher velocities
469 | // correspond to thinner strokes.
470 | float newWidth = strokeWidth(velocity);
471 |
472 | // The Bezier's width starts out as last curve's final width, and
473 | // gradually changes to the stroke width just calculated. The new
474 | // width calculation is based on the velocity between the Bezier's
475 | // start and end mPoints.
476 | addBezier(curve, mLastWidth, newWidth);
477 |
478 | mLastVelocity = velocity;
479 | mLastWidth = newWidth;
480 |
481 | // Remove the first element from the list,
482 | // so that we always have no more than 4 mPoints in mPoints array.
483 | recyclePoint(mPoints.remove(0));
484 |
485 | recyclePoint(c2);
486 | recyclePoint(c3);
487 |
488 | } else if (pointsCount == 1) {
489 | // To reduce the initial lag make it work with 3 mPoints
490 | // by duplicating the first point
491 | TimedPoint firstPoint = mPoints.get(0);
492 | mPoints.add(getNewPoint(firstPoint.x, firstPoint.y));
493 | }
494 | this.mHasEditState = true;
495 | }
496 |
497 | private void addBezier(Bezier curve, float startWidth, float endWidth) {
498 | mSvgBuilder.append(curve, (startWidth + endWidth) / 2);
499 | ensureSignatureBitmap();
500 | float originalWidth = mPaint.getStrokeWidth();
501 | float widthDelta = endWidth - startWidth;
502 | float drawSteps = (float) Math.ceil(curve.length());
503 |
504 | for (int i = 0; i < drawSteps; i++) {
505 | // Calculate the Bezier (x, y) coordinate for this step.
506 | float t = ((float) i) / drawSteps;
507 | float tt = t * t;
508 | float ttt = tt * t;
509 | float u = 1 - t;
510 | float uu = u * u;
511 | float uuu = uu * u;
512 |
513 | float x = uuu * curve.startPoint.x;
514 | x += 3 * uu * t * curve.control1.x;
515 | x += 3 * u * tt * curve.control2.x;
516 | x += ttt * curve.endPoint.x;
517 |
518 | float y = uuu * curve.startPoint.y;
519 | y += 3 * uu * t * curve.control1.y;
520 | y += 3 * u * tt * curve.control2.y;
521 | y += ttt * curve.endPoint.y;
522 |
523 | // Set the incremental stroke width and draw.
524 | mPaint.setStrokeWidth(startWidth + ttt * widthDelta);
525 | mSignatureBitmapCanvas.drawPoint(x, y, mPaint);
526 | expandDirtyRect(x, y);
527 | }
528 |
529 | mPaint.setStrokeWidth(originalWidth);
530 | }
531 |
532 | private ControlTimedPoints calculateCurveControlPoints(TimedPoint s1, TimedPoint s2, TimedPoint s3) {
533 | float dx1 = s1.x - s2.x;
534 | float dy1 = s1.y - s2.y;
535 | float dx2 = s2.x - s3.x;
536 | float dy2 = s2.y - s3.y;
537 |
538 | float m1X = (s1.x + s2.x) / 2.0f;
539 | float m1Y = (s1.y + s2.y) / 2.0f;
540 | float m2X = (s2.x + s3.x) / 2.0f;
541 | float m2Y = (s2.y + s3.y) / 2.0f;
542 |
543 | float l1 = (float) Math.sqrt(dx1 * dx1 + dy1 * dy1);
544 | float l2 = (float) Math.sqrt(dx2 * dx2 + dy2 * dy2);
545 |
546 | float dxm = (m1X - m2X);
547 | float dym = (m1Y - m2Y);
548 | float k = l2 / (l1 + l2);
549 | if (Float.isNaN(k)) k = 0.0f;
550 | float cmX = m2X + dxm * k;
551 | float cmY = m2Y + dym * k;
552 |
553 | float tx = s2.x - cmX;
554 | float ty = s2.y - cmY;
555 |
556 | return mControlTimedPointsCached.set(getNewPoint(m1X + tx, m1Y + ty), getNewPoint(m2X + tx, m2Y + ty));
557 | }
558 |
559 | private float strokeWidth(float velocity) {
560 | return Math.max(mMaxWidth / (velocity + 1), mMinWidth);
561 | }
562 |
563 | /**
564 | * Called when replaying history to ensure the dirty region includes all
565 | * mPoints.
566 | *
567 | * @param historicalX the previous x coordinate.
568 | * @param historicalY the previous y coordinate.
569 | */
570 | private void expandDirtyRect(float historicalX, float historicalY) {
571 | if (historicalX < mDirtyRect.left) {
572 | mDirtyRect.left = historicalX;
573 | } else if (historicalX > mDirtyRect.right) {
574 | mDirtyRect.right = historicalX;
575 | }
576 | if (historicalY < mDirtyRect.top) {
577 | mDirtyRect.top = historicalY;
578 | } else if (historicalY > mDirtyRect.bottom) {
579 | mDirtyRect.bottom = historicalY;
580 | }
581 | }
582 |
583 | /**
584 | * Resets the dirty region when the motion event occurs.
585 | *
586 | * @param eventX the event x coordinate.
587 | * @param eventY the event y coordinate.
588 | */
589 | private void resetDirtyRect(float eventX, float eventY) {
590 |
591 | // The mLastTouchX and mLastTouchY were set when the ACTION_DOWN motion event occurred.
592 | mDirtyRect.left = Math.min(mLastTouchX, eventX);
593 | mDirtyRect.right = Math.max(mLastTouchX, eventX);
594 | mDirtyRect.top = Math.min(mLastTouchY, eventY);
595 | mDirtyRect.bottom = Math.max(mLastTouchY, eventY);
596 | }
597 |
598 | private void setIsEmpty(boolean newValue) {
599 | mIsEmpty = newValue;
600 | if (mOnSignedListener != null) {
601 | if (mIsEmpty) {
602 | mOnSignedListener.onClear();
603 | } else {
604 | mOnSignedListener.onSigned();
605 | }
606 | }
607 | }
608 |
609 | private void ensureSignatureBitmap() {
610 | if (mSignatureBitmap == null) {
611 | mSignatureBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
612 | Bitmap.Config.ARGB_8888);
613 | mSignatureBitmapCanvas = new Canvas(mSignatureBitmap);
614 | }
615 | }
616 |
617 | private int convertDpToPx(float dp) {
618 | return Math.round(getContext().getResources().getDisplayMetrics().density * dp);
619 | }
620 |
621 | public interface OnSignedListener {
622 | void onStartSigning();
623 |
624 | void onSigned();
625 |
626 | void onClear();
627 | }
628 |
629 | public List getPoints() {
630 | return mPoints;
631 | }
632 | }
633 |
--------------------------------------------------------------------------------
/signature-pad/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------