The Android UI design family's custom Drawview component implements digital signature effects (5) _android

Source: Internet
Author: User

There is a new requirement in the recent project, users in the end of the transaction needs to enter payment password payment, to allow users to sign their own signature, brought to the digital signature of this thing, feeling a little tall, and then think of the principle of digital signature is not too complex, the main principle is to make use of the view of the drawing principle, Display the user's finger movement trajectory on the screen, then convert the trajectory view shown on the screen to a picture, and save the image locally or upload it to the server ...
Or the old rules, first look at the Engineering directory:

public class Drawview extends View {/** * Signature brush */private Paint Paint; 
 /** * Signature Canvas/private Canvas Cachecanvas; 
 /** * Brush Path * * Private path path; 
 /** * Cache Picture * * Private Bitmap Cachebitmap; 
 /** * Picture Width */private int width; 
 /** * Picture Height * * private int height; 
 /** * finger touch screen when the x,y coordinate * * Private float xdown, Ydown; 
 
 /** * is drawing * * Private Boolean isdrawing = false; 
 
 /** * Default brush color/private int paintcolor = Color.cyan; 
 
 /** * Default Artboard background color * * Private int canvascolor = Color.parsecolor ("#bbccaa"); 
  Public Drawview (context, int width, int height) {super (context); 
  This.width = width; 
  This.height = height; 
 Initwedgits (); 
   }/** * Initialization component */private void Initwedgits () {try {paint = new paint (Paint.dither_flag); 
   Set anti-aliasing Paint.setantialias (true); 
   Set Brush width paint.setstrokewidth (3); 
   Paint.setdither (TRUE); Set Style Paint.setstyle (paint.stYle. 
   STROKE); 
   Paint.setstrokejoin (Paint.Join.ROUND); 
   Paint.setstrokecap (Paint.Cap.ROUND); 
   Brush color Paint.setcolor (paintcolor); 
   Plot path Path = new Path (); 
   Create an empty cache picture Cachebitmap = Bitmap.createbitmap (width, height, config.argb_8888); 
  Draw the canvas contents to the empty cache picture Cachecanvas = new Canvas (CACHEBITMAP); 
  catch (Exception e) {e.printstacktrace ();  } @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {super.onsizechanged (W, H, OLDW, 
 OLDH); 
 
  } @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas); 
  Canvas.drawcolor (Canvascolor); 
  Canvas.drawbitmap (cachebitmap, 0, 0, paint); 
 Canvas.drawpath (path, paint); 
  @Override public boolean ontouchevent (Motionevent event) {//record the X coordinate of the final float x = Event.getx () When the finger is pressed on the screen; 
  Record the y-coordinate of the screen when the finger is pressed final float y = event.gety (); 
   Switch (event.getaction ()) {case Motionevent.action_down://When the finger is pressed to clear before the setting Path.reset (); Set upPath starting point Path.moveto (x, y); 
   Xdown = x; 
   Ydown = y; 
   Isdrawing = true; 
  Break 
   Case Motionevent.action_move://Move Next point Path.quadto (Xdown, Ydown, x, y); 
   Reset start Xdown = x; 
   Ydown = y; 
   Isdrawing = true; 
  Break 
   Case MotionEvent.ACTION_UP:path.lineTo (Xdown, Ydown); 
   Draw the path Cachecanvas.drawpath (path, paint) when the finger is raised; 
   Path reset Path.reset (); 
   Isdrawing = false; 
  Break 
  Default:break; 
  //Refresh interface invalidate (); 
 return true; /** * Set Brush color * * @param color * BRUSH color * * public void Setpaintcolor (int color) {Paintcolor = Co 
 Lor /** * Set Artboard color * * @param color * Artboard colors */public void Setcanvascolor (int color) {Canvascolor = 
 Color /** * Back to painting state * @return "true: Drawing" "false: Drawing Complete" * * public boolean getdrawstate () {return isdrawing 
 ; /** * Returns BITMAP * * @return returns the painted picture * * Public Bitmap Getbitmap () {return CACHEBITMAP  } 
}

Drawview code comments are very clear, I would like to say the drawview of the implementation of the logic bar, Drawview inherited view that is to have all the functions of view, to achieve the picture will be achieved OnDraw () method, To achieve the trajectory of the finger on the screen to draw the trajectory coordinates need to obtain, so need to rewrite the Ontouchevent () method, focusing on the Ontouchevent () method. We draw the starting point when the finger is pressed, but we need to call the Path.reset () method before we draw the starting point, to prevent the path from being redrawn two times, and the path's MoveTo method is to draw the starting point of the current touch event, and then invoke the Invalidate () method to refresh the interface. When the finger moves, call the Path.quadto () method, which means append, append the new coordinates to path, then call the Invalidate () method to refresh the interface after the finger is moved, and finally when the finger is raised, To draw the trajectory in the current event cycle to the artboard Cachecanvas, and finally call the invalidate () method for the interface refresh, so once the finger movement trajectory is completed, when the next time to draw, is to repeat the above operation ...

Let's take a look at the use of Drawview, first look at the layout file:

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Chemas.android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" Fill_parent "Android: layout_height= "Fill_parent" android:background= "#ffffff" > <textview android:id= "@+id/title" Android:layo Ut_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "please draw signature" android:textsize= "18SP" Andro Id:layout_margin= "5dip" android:gravity= "center" android:textcolor= "#000000"/> <framelayout android:id = "@+id/contents" android:layout_width= "fill_parent" android:layout_height= "0dip" android:layout_weight= "1" and roid:layout_gravity= "center" android:background= "#aabbcc" > </FrameLayout> <button android:layout_w Idth= "Match_parent" android:layout_height= "Wrap_content" android:onclick= "Save" android:text= "Saving signature"/> </L Inearlayout> 

There is no use of our custom Drawview in the layout file at first glance, but don't worry. I used the method of adding Drawview in the framelayout dynamically, so let's look at the code implementation in Mainactivity:

public class Mainactivity extends activity {private framelayout framelayout; 
 Private Drawview Drawview; 
 
 Private TextView title; /** called the activity is a. 
  * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
  Setcontentview (R.layout.main); 
 Initwedgits (); }/** * Initialization component */private void Initwedgits () {try {framelayout = (framelayout) Findviewbyid (r.id.conte 
   NTS); 
   title = (TextView) Findviewbyid (r.id.title); Title.settext (html.fromhtml) ("<b>china China <tt> China </tt></b>china is really great!" 
 
  ")); 
  catch (Exception e) {e.printstacktrace (); @Override public void Onwindowfocuschanged (Boolean hasfocus) {Drawview = new Drawview (Mainactivity.this, F 
  Ramelayout.getwidth (), Framelayout.getheight ()); 
 Framelayout.addview (Drawview); /** * Save Picture * * @param view */public void Save (view view) {try {file = new FilE (Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/handle.png"); 
   if (file.exists ()) {file.delete (); 
   } file.createnewfile (); if (Drawview.getbitmap (). Compress (Compressformat.png, new FileOutputStream (file)) {Toast.maketext (getapplicat 
   Ioncontext (), "Picture saved successfully", 1000. Show (); 
  } catch (Exception e) {e.printstacktrace (); 
 } 
 } 
}

The code in the mainactivity is not good to explain, I believe you can understand, the most important is in the Save method using the bitmap compress () method, is the picture stored in the file, when we signed the end of the click to save the signature button, The signature picture is saved in the local file, of course, if you want to upload to the backend server is not difficult, is to use an asynchronous operation to upload the image of the line ...

Description : When you run the program, you will see China Chinese is really great! of Chinese and China is the effect of bold, because there is a demand for the project to make the Chinese characters are also bold, online find some methods, but the English and the number has effect on the Chinese temporarily no effect, I also have no intention to see the source of the comments, The comments inside the bold text description, I clicked in, the results found in the comments in the label is <tt></tt>, when the brain turned to estimate <tt> tags can be achieved on the Chinese character of the bold effect, oh, kungfu do not pay, the <TT > label put into the <b> inside has been tested, it really has effect, oh, then happy bad, and now happy again, (*^__^*) Xi hee ...

OK, now let's run the program and look at the effect chart:

Draw Signature:

When you click on the Save button, go to the gallery to see:

Well, the digital signature of the explanation to here, thank you for your reading.

SOURCE Download: Android UI to achieve digital signature effect

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.