Android based on Google zxing to achieve a variety of two-dimensional code scanning effect _android

Source: Internet
Author: User
Tags getcolor gety

With the arrival of micro-letter, two-dimensional code more and more hot, everywhere can see two-dimensional code, such as the mall inside, KFC, restaurants and so on, for two-dimensional code scanning we are using Google's Open source framework zxing, we can go to http://code.google.com/p/zxing/ Download source and jar package, before my project two-dimensional code scanning function only to achieve the scanning function, its UI is really its ugly, a good application software, its UI interface should be accepted by the public, otherwise people will not use your software, so the application of software functions and interface is very important, such as micro-letters, I believe that the micro-letter UI is imitated by many application software, and I imitate the micro-scan two-dimensional code effect. Although there is no micro-letter to do so exquisite, but the effect is still possible, so the code to modify their own UI and scan two-dimensional code to share to everyone, one of their future projects encountered the same function directly copy to use, The second is to have not joined the two-dimensional code function of a reference, standing on the shoulders of giants, Haha, I was also standing on the shoulders of giants to add this function, and then follow me step-by-step to achieve this function, inside to go except for a lot of unnecessary documents

Let's look at the structure of the project first.

    • If your project also wants to join this feature, You will directly copy Com.mining.app.zxing.camera,com.mining.app.zxing.decoding,com.mining.app.zxing.view these three packages into your project, and then introduce the corresponding resources to go in, I also from my project , the package name does not change, of course, also need to quote Zxing.jar
    • There is a mipcaactivitycapture in the Com.example.qr_codescan package that is also directly introduced into my previous project's code, which mainly deals with scanning interface classes, such as the success of the scan with sound and vibration, etc. The main focus is on the Handledecode (result results, Bitmap Barcode) method, which passes the scanned results and the Bitmap parameters of the two-dimensional code to Handledecode after the scan is completed. Bitmap barcode) Inside, we just need to write in the corresponding processing code, the other places do not have to change, I am here to handle the scan results and scanned photos
/** 
 * Processing Scan results * 
 @param result 
 * @param barcode 
/public void Handledecode Barcode) { 
  inactivitytimer.onactivity (); 
  Playbeepsoundandvibrate (); 
  String resultstring = Result.gettext (); 
  if (Resultstring.equals ("")) { 
    Toast.maketext (mipcaactivitycapture.this, "Scan failed!", Toast.length_short). Show (); 
  } else { 
    Intent resultintent = new Intent (); 
    Bundle Bundle = new Bundle (); 
    Bundle.putstring ("result", resultstring); 
    Bundle.putparcelable ("Bitmap", barcode); 
    Resultintent.putextras (bundle); 
    This.setresult (RESULT_OK, resultintent); 
  } 
  MipcaActivityCapture.this.finish (); 
} 

I mipcaactivitycapture the layout of the interface made its own changes, first look at the effect of the map, mainly used to framelayout, inside the nesting relativelayout.

The layout code is as follows

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout xmlns:android= "http://schemas.android.com/apk/res/" 
    Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "> <relativelayout Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" > <surfaceview android:id= "@+id/preview_view" android:layout_width= "fill_parent" android:layout_height= "Fill_parent" Android:la 
      yout_gravity= "center"/> <com.mining.app.zxing.view.viewfinderview android:id= "@+id/viewfinder_view" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"/> <include Andr Oid:id= "@+id/include1" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Androi D:layout_alignparenttop= "true" layout= "@layout/activity_title"/> </RelativeLayout> </framelayout 
 >

Inside I'll put the top part of the interface in another layout, and then include it, because this activity_title is also available for other activity in my project, and I copied it directly.

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:background=" @drawable/mm Title_bg_alpha "> <button android:id=" @+id/button_back "android:layout_width=" 75.0dip "android:t Ext= "Back to android:background=" @drawable/mm_title_back_btn "android:textcolor=" @android: Color/white "android: layout_height= "Wrap_content" android:layout_centervertical= "true" android:layout_marginleft= "2dip"/> &L T TextView android:id= "@+id/textview_title" android:layout_width= wrap_content "android:layout_height=" Wrap_c Ontent "android:layout_alignbaseline=" @+id/button_back "android:layout_alignbottom=" @+id/button_back "Andro" Id:layout_centerhorizontal= "true" android:gravity= "center_vertical" android:text= "Two-dimensional code scanning" android:textcolor= 
    "@android: Color/white"Android:textsize= "18sp"/> </RelativeLayout> 
 

In my demo, there is a main interface mainactivity, inside a button, a imageview and a TextView, click the button into the two-dimensional code scanning interface, when the scan OK, back to the main interface, Display the results of the scan to TextView, display the picture to the ImageView, and then you can not process the picture, I have the accompanying picture here, the layout of the main interface is very simple as follows

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:backg" round= "#ffe1e0de" > <button android:id= "@+id/button1" android:layout_width= "Fill_parent" Android 
    : layout_height= "Wrap_content" android:layout_alignparenttop= "true" android:text= "scan two-dimensional code"/> <textview Android:id= "@+id/result" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Andro id:layout_below= "@+id/button1" android:lines= "2" android:gravity= "Center_horizontal" "android:textColor=" @an Droid:color/black "android:textsize=" 16sp "/> <imageview android:id=" @+id/qrcode_bitmap "Android : layout_width= "fill_parent" android:layout_height= "Fill_parent" android:layout_alignparentleft= "true" Andro id:layout_below= "@+id/result"/> </relAtivelayout> 
 

The code inside the

Mainactivity is as follows, and the functionality inside has been said

Package Com.example.qr_codescan; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.graphics.Bitmap; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
Import Android.widget.ImageView; 
 
Import Android.widget.TextView; 
  public class Mainactivity extends activity {private final static int scannin_grequest_code = 1; 
  /** * Show Scan results * * Private TextView Mtextview; 
   
 
  /** * Show scanned Pictures * * Private imageview Mimageview; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.activity_main);  
    Mtextview = (TextView) Findviewbyid (R.id.result); 
     
    Mimageview = (ImageView) Findviewbyid (R.ID.QRCODE_BITMAP); Click on the button to jump to the two-dimensional code scanning interface, here with the Startactivityforresult jump//scan finished after the interface button Mbutton = (button) Findviewbyid (r.id.button1 
    ); Mbutton.setonclickliStener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent = new 
        Intent (); 
        Intent.setclass (Mainactivity.this, Mipcaactivitycapture.class); 
        Intent.setflags (Intent.flag_activity_clear_top); 
      Startactivityforresult (Intent, Scannin_grequest_code); 
  } 
    }); @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onact 
    Ivityresult (Requestcode, ResultCode, data); Switch (requestcode) {case Scannin_grequest_code:if (ResultCode = = RESULT_OK) {Bundle Bundle = data. 
        Getextras (); 
        Displays the contents of the scan Mtextview.settext (bundle.getstring ("result")); 
      Display Mimageview.setimagebitmap ((Bitmap) Data.getparcelableextra ("Bitmap")); 
    } break; 
 } 
  }   
 
}

The above code is relatively simple, but in order to make a scan box like a micro-letter, tightly above the code is not that kind of effect, We must rewrite the Com.mining.app.zxing.view package under the Viewfinderview class, micro-letter inside are used pictures, I am drawing out, the code comments more clearly, we see the code directly, I believe you can understand, if you want to modify the size of the scan box, to Camerama Inside the Nager class, modify the

* * Copyright (C) 2008 zxing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); 
 * You could not use this file, except in compliance with the License. * You may obtain a copy of the License at * * * unless required by applicable and agreed to, writing are * Distributed under the License is distributed on ' as is ' basis, * without warranties OR CONDITIONS to any KIND 
 , either express or implied. 
 * The License for the specific language governing permissions and * limitations under the License. 
 
* * Package Com.mining.app.zxing.view; 
Import java.util.Collection; 
 
Import Java.util.HashSet; 
Import Android.content.Context; 
Import android.content.res.Resources; 
Import Android.graphics.Bitmap; 
Import Android.graphics.Canvas; 
Import Android.graphics.Color; 
Import Android.graphics.Paint; 
Import Android.graphics.Rect; 
Import Android.graphics.Typeface; 
Import Android.util.AttributeSet; 
 Import Android.view.View;
Import Com.example.qr_codescan. 
R 
Import Com.google.zxing.ResultPoint; 
 
Import Com.mining.app.zxing.camera.CameraManager; /** * This view is overlaid to the top of the camera preview. It adds the viewfinder * rectangle and partial transparency outside it, as as the The laser scanner * Animation and R 
 Esult points. 
  * */Public final class Viewfinderview extends View {private static final String TAG = "Log"; 
  /** * Refresh the interface time * * Private static final long animation_delay = 10L; 
 
  private static final int OPAQUE = 0xFF; 
   
  /** * Four green corner corresponding length * * private int screenrate; 
  /** * Four green corner corresponding width * * private static final int corner_width = 10; 
   
  /** * The width of the middle line in the scan box * * private static final int middle_line_width = 6; 
   
  /** * Scan box in the middle of the gap with the scan box/private static final int middle_line_padding = 5; 
   
  /** * The line in the middle of each refresh moving distance * * private static final int speen_distance = 5; /** * Mobile Screen density * * * private static float density; 
  /** * Font Size * * private static final int text_size = 16; 
   
  /** * Font distance under the Scan box * * private static final int text_padding_top = 30; 
   
  /** * A reference to the object of the brush * * Private Paint Paint; 
   
  /** * The top position of the middle sliding line * * private int slidetop; 
   
  /** * The bottom position of the middle sliding line */private int slidebottom; 
  Private Bitmap Resultbitmap; 
  private final int maskcolor; 
   
  private final int resultcolor; 
  private final int resultpointcolor; 
  Private collection<resultpoint> possibleresultpoints; 
 
  Private collection<resultpoint> lastpossibleresultpoints; 
   
  Boolean Isfirst; 
     
    Public Viewfinderview (context, AttributeSet attrs) {Super (context, attrs); 
    Density = context.getresources (). Getdisplaymetrics (). density; 
 
    Converts pixels to DP screenrate = (int) (density); 
    Paint = new paint (); 
    Resources of resources = getresources (); MaskColor = Resources.getcolor (r.color.viewfiNder_mask); 
 
    Resultcolor = Resources.getcolor (R.color.result_view); 
    Resultpointcolor = Resources.getcolor (r.color.possible_result_points); 
  possibleresultpoints = new hashset<resultpoint> (5); @Override public void OnDraw (Canvas Canvas) {//Intermediate scan box, you need to modify the size of the scan box to Cameramanager inside to modify the Rect frame = came 
    Ramanager.get (). Getframingrect (); 
    if (frame = = null) {return; 
      ///Initialize the top and bottom if (!isfirst) {Isfirst = true of the middle line slide; 
      Slidetop = Frame.top; 
    Slidebottom = Frame.bottom; 
    //Get the screen width and height int width = canvas.getwidth (); 
 
    int height = canvas.getheight (); 
     
    Paint.setcolor (Resultbitmap!= null? resultcolor:maskcolor); Draw the shadow of the outside of the scan box, a total of four parts, the top of the scan box above to the screen, scan the box below the screen//scan box to the left side of the screen to the left of the scan box to the right canvas.drawrect (0, 0, width, frame.top, 
    Paint); 
    Canvas.drawrect (0, Frame.top, frame.left, Frame.bottom + 1, paint); Canvas.drawrect (frame.right + 1, frame.top, width,Frame.bottom + 1, paint); 
     
     
 
    Canvas.drawrect (0, Frame.bottom + 1, width, height, paint); if (Resultbitmap!= null) {//Draw the opaque result bitmap over the scanning rectangle Paint.setalpha (Opaq 
      UE); 
    Canvas.drawbitmap (Resultbitmap, Frame.left, frame.top, paint); 
      else {//Draw the corner on the edge of the scan box, a total of 8 parts paint.setcolor (Color.green); 
      Canvas.drawrect (Frame.left, frame.top, Frame.left + screenrate, Frame.top + corner_width, paint); 
      Canvas.drawrect (Frame.left, frame.top, Frame.left + corner_width, Frame.top + screenrate, paint); 
      Canvas.drawrect (Frame.right-screenrate, Frame.top, frame.right, Frame.top + corner_width, paint); 
      Canvas.drawrect (Frame.right-corner_width, Frame.top, frame.right, Frame.top + screenrate, paint); 
      Canvas.drawrect (Frame.left, frame.bottom-corner_width, Frame.left + screenrate, frame.bottom, paint); Canvas.draWrect (Frame.left, frame.bottom-screenrate, Frame.left + corner_width, frame.bottom, paint); 
      Canvas.drawrect (Frame.right-screenrate, Frame.bottom-corner_width, Frame.right, Frame.bottom, paint); 
 
       
      Canvas.drawrect (Frame.right-corner_width, Frame.bottom-screenrate, Frame.right, Frame.bottom, paint); 
      Draw the middle of the line, each time refreshing the interface, the middle of the line moving down speen_distance slidetop + = speen_distance; 
      if (slidetop >= frame.bottom) {slidetop = Frame.top; } canvas.drawrect (Frame.left + middle_line_padding, SLIDETOP-MIDDLE_LINE_WIDTH/2, Frame.right-middle_line_paddi 
       
       
      Ng,slidetop + MIDDLE_LINE_WIDTH/2, paint); 
      Draw the text below the scan box Paint.setcolor (color.white); 
      Paint.settextsize (text_size * density); 
      Paint.setalpha (0x40); 
      Paint.settypeface (Typeface.create ("System", Typeface.bold)); Canvas.drawtext (Getresources (). getString (R.string.scan_text), Frame.left, (float) (Frame.botTom + (float) text_padding_top *density), paint); 
      collection<resultpoint> currentpossible = possibleresultpoints; 
      collection<resultpoint> currentlast = lastpossibleresultpoints; 
      if (Currentpossible.isempty ()) {lastpossibleresultpoints = null; 
        else {possibleresultpoints = new hashset<resultpoint> (5); 
        Lastpossibleresultpoints = currentpossible; 
        Paint.setalpha (OPAQUE); 
        Paint.setcolor (Resultpointcolor); 
              for (Resultpoint point:currentpossible) {canvas.drawcircle (Frame.left + point.getx (), Frame.top 
        + point.gety (), 6.0f, paint); 
        } if (Currentlast!= null) {Paint.setalpha (OPAQUE/2); 
        Paint.setcolor (Resultpointcolor);  for (Resultpoint point:currentlast) {canvas.drawcircle (Frame.left + point.getx (), Frame.top + 
        Point.gety (), 3.0f, paint); 
 
    } 
      }   
      Only refresh the contents of the scan box, other places do not refresh postinvalidatedelayed (Animation_delay, Frame.left, Frame.top, Frame.right, 
       
    Frame.bottom); 
    } public void Drawviewfinder () {resultbitmap = null; 
  Invalidate (); 
   }/** * Draw a bitmap with the result points highlighted instead of the live * scanning display. 
   * * @param barcode * An image of the decoded barcode. 
    */public void Drawresultbitmap (Bitmap barcode) {resultbitmap = barcode; 
  Invalidate (); 
  public void Addpossibleresultpoint (Resultpoint point) {possibleresultpoints.add (point); 
 } 
 
}

In the code above, the middle of the line micro-letter is used in the picture, I am here to draw, if you want to more simulation points will be the following code

Canvas.drawrect (Frame.left + middle_line_padding, SLIDETOP-MIDDLE_LINE_WIDTH/2, frame.right-middle_line_padding, Slidetop + MIDDLE_LINE_WIDTH/2, paint); 

Change into

Rect linerect = new Rect (); 
      Linerect.left = Frame.left; 
      Linerect.right = frame.right; 
      Linerect.top = Slidetop; 
      Linerect.bottom = Slidetop +; 
      Canvas.drawbitmap ((bitmapdrawable) (Getresources (). getdrawable (R.drawable.qrcode_scan_line)). GetBitmap (), NULL , Linerect, paint); 

The scan line oneself to the micro-letter inside look for, I posted the distortion, download micro-letter apk, the suffix name into a zip, and then decompression on the line
The code of the font below the scan frame needs to be modified, this way can be automatically arranged in the middle according to the font, if the word is too long I did not deal with, that to automatically wrap, you can handle

Paint.setcolor (color.white);  
Paint.settextsize (text_size * density);  
Paint.setalpha (0x40);  
Paint.settypeface (typeface.default_bold);  
String text = Getresources (). getString (R.string.r.string.scan_text); 
float textWidth = paint.measuretext (text); 
 

Run the screen screenshot, the middle of the Green Line will move up and down, and the effect of micro-letter is similar, of course, you need to run the corresponding permissions issues.

This is the entire content of this article, I hope to learn more about Android software programming help.

Related Article

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.