Android Project Combat (28): zxing Two-dimensional code implementation and optimization

Source: Internet
Author: User

Original: Android Project Combat (28): zxing Two-dimensional code implementation and optimization

Objective:

Many years ago contacted Zxing realize two-dimensional code, did not think that the use of today's project is still the use of zxing, Baidu, it is such a cow thing.

Of course, we may only use QR code to scan and generate two functions, so do not have to download the full jar package, use the simplified version, the following can be seen.

This article describes: 1, if the rapid integration of zxing in the project, the implementation of scanning and generation of QR code function

2, according to the project needs to modify the source code to achieve our requirements and optimize

One, fast integration zxing two-dimensional code

1. Download library file: http://download.csdn.NET/detail/u013210620/9036083, file name: barcodetest

When the download is complete, you can see:

  

We copy the required items from these files to our own projects, starting with the following:

①, res directory: Raw folder entire copy to personal item relative location

②, RES----In the values directory: the contents of the Ids.xml file are all copied to the relative position of the individual items, the individual items are not copied directly to the relative location

③, RES---In the values directory: the contents of the Colors.xml file are all copied to the relative position of the individual item

④, RES----Layouts directory: Camera.xml layout files copied to individual items relative location

⑤, Res--and drawable_mdpi: Navbar.9.png pictures copied to the relative position of the individual items, this picture is the title bar background picture, it is recommended to change to Navbar.png do not use. 9 pics

⑥, libs directory: Zxing.jar file copied to the relative location of personal items, and right click on the AS Library

⑦, SRC-----com directory: zxing folder copy to personal project relative location, will error, modify R directory structure can

⑧, Androidmanifest.xml file added (QR Code scan activity, this need to be modified later, to achieve their own requirements)

<activity android:name="com.zxing.activity.CaptureActivity"/>

Add permissions in ⑨, androidmanifest.xml files

<uses-permission android:name="android.permission.CAMERA" />    < Uses-permission android:name="android.permission.VIBRATE" />    < Uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE " />

2, the preparation work completed, the following start to write demo

Now the demand is a main interface Mainactivity.java there are two buttons, respectively jump to generate two-dimensional code interface and scan the QR code interface

  

Then start writing the implementation of the two activity functions separately:

①, generate two-dimensional code

Write the layout file first, a picture, a Start button, an input box (QR code needs to be generated according to the text information, no text information can not be generated)

<?xml version="1.0"encoding="Utf-8"? ><linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="match_parent"Android:layout_height="match_parent"android:orientation="Vertical"Tools:context="com.maiji.zxingdemo.CreateActivity"> <ImageView Android:id="@+id/create_img"Android:layout_width="300DP"Android:layout_height="300DP"Android:scaletype="Fitxy"android:layout_gravity="Center_horizontal"/> <Button Android:id="@+id/create_btn"Android:layout_width="wrap_content"Android:layout_height="wrap_content"android:layout_gravity="Center_horizontal"Android:text="start generating QR code"/> <EditText Android:id="@+id/create_edit"Android:layout_width="match_parent"Android:layout_height="wrap_content"/></linearlayout>
Activity_create.xml

Activity code: The code is relatively simple, not explained in this

PrivateImageView create_img; PrivateButton create_btn; PrivateEditText Create_edit; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_create);        Initview ();    Initevent (); }    Private voidinitevent () {Create_btn.setonclicklistener ( This); }    Private voidInitview () {create_img=(ImageView) Findviewbyid (r.id.create_img); CREATE_BTN=(Button) Findviewbyid (R.ID.CREATE_BTN); Create_edit=(EditText) Findviewbyid (R.id.create_edit); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id.create_btn:string Content="" ; if(Create_edit.gettext (). toString (). Equals ("") {Toast.maketext ( This,"Please enter two-dimensional code information", Toast.length_short). Show (); return; } content=Create_edit.gettext (). toString (); Try {                    //generate a two-dimensional code picture, the first parameter is the content of the QR code, the second parameter is a square picture of the edge length, in pixelsBitmap Qrcodebitmap = encodinghandler.createqrcode (content, -); if(qrcodebitmap!=NULL) {create_img.setimagebitmap (QRCODEBITMAP); }Else{Toast.maketext ( This,"failed to generate the QR code", Toast.length_short). Show (); }                } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                 Break; }    }     Public byte[] bitmap2bytes (Bitmap BM) {Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Bm.compress (Bitmap.CompressFormat.PNG, -, BAOs); returnBaos.tobytearray (); }

:

         

②, scan QR code

This is even easier, just open an activity provided by zxing and fetch the scanned string.

See the key code for scanactivity (scan activity)

Private TextView zxing_content;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_scan);
Zxing_content = (TextView) Findviewbyid (r.id.zxing_content);
Intent Startscan = new Intent (this,captureactivity.class);
Startactivityforresult (Startscan, 0); //actually opened a scan activity that zxing provided to us, of course, we'll make some optimizations for this activity later on.

}

/**
* Sweep, after successful return value to judge
*/
@Override
public void Onactivityresult (int requestcode, int resultcode, Intent data) {
Super.onactivityresult (Requestcode, ResultCode, data);
if (ResultCode = =-1) {
String result = Data.getextras (). getString ("result");
Zxing_content.settext (result); Display the data obtained by scanning the QR code
}
}

Layout file:

<?xml version="1.0"encoding="Utf-8"? ><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"Tools:context="com.maiji.zxingdemo.ScanActivity"> <TextView Android:id="@+id/zxing_content"Android:layout_width="wrap_content"Android:layout_height="wrap_content"android:layout_centerinparent="true"android:textsize="30SP"/></relativelayout>
Activity_scan

:

        

Second, modify the source code to achieve the needs of the project

1, modify the scan QR code interface

Corresponding to the Zxing-->activity-->captureactivity.java, the layout file is Camera.xml

So the modification interface only needs to be modified in the Camera.xml file.

Nothing but the original "Cancel" Cancel button removed, the top of the title bar for a change.

The layout has a <SurfaceView> control to display a preview of the camera's shot, which can be changed to full-screen display or local display

<com.zxing.view.ViewfinderView> control, that is, the scan box, the default is the aspect ratio of 1:1.5, the actual need to modify the width of the high, described below

2. Modify the width and height of the scan box

After the 1th step is done, we will not be able to modify the width of the scan box.

Modify the Scan box width is very simple, find the Zxing-->camera-->cameramanager.java file

Here are the more top-of-the-line code to see:

  

  Private Static int  - ;   Private Static int  - ;   Private Static int 480 ;   Private Static int 480;

The value of these four properties is the width of the scan box, and then can be directly modified according to demand, of course, this value in different resolutions of the device width and height is inconsistent, if necessary, you can do a unit conversion

  

  public Static  int DP2PX (context context,float  dp) {    float scale = context.getresources (). Getdisplaymetrics (). density;     return (int0.5f);  }

: I modified the minimum maximum width height of the scan box to be consistent, and the "Cancel" Cancel button was deleted from the Camera.xml layout

  

3. Add text hints to the scan box

Look at the scanning interface, you will find a text hint below the scan box. Then we have no, need to add

Find Zxing-->view-->viewfinderview.java

Here is the class of the Custom Scan box

Find the code:

  

2 1 1 2 , paint);      Collection<ResultPoint> currentpossible = possibleresultpoints;

Between these two lines of code we draw a text hint

Canvas.drawrect (Frame.left + 2, middle-1, frame.right-1, Middle + 2, paint);
Textpaint textpaint = new Textpaint ();      Textpaint.setargb (0xFF, 0xFF, 0xff,0xff);   Font Color      textpaint.settextsize (+);    Font size      Textpaint.setantialias (true);  Set antialiasing, otherwise the handwriting will be very vague      staticlayout layout = new Staticlayout ("The two-dimensional stacking into the box, you can automatically scan", Textpaint,              Frame.right-frame.left, layout.alignment.align_normal,1.0f,0.0f,true);      Canvas.translate (frame.left+5, (float) (Frame.bottom + (float) 30)); Draw the starting position      Layout.draw (canvas);
    collection<resultpoint> currentpossible = possibleresultpoints;

Then look at the scanning interface:

  

4, solve the scanning interface camera preview stretching deformation problem

To achieve the above steps of optimization, the careful classmate may find that if we give Surfaceview a full screen display (can see a lot of camera screen), you will find the camera shot out of the preview of some stretching deformation

Cause:After zxing horizontal screen, the camera's code is also the parameters set by the horizontal screen code

Optimization method: Find zxing-->camera--> Cameraconfigurationmanager.java

Initfromcameraparameters method, in Log.d (TAG,"Screen Resolution:"+screenresolution); add point Screenresolutionforcamera after this sentence=NewPoint (); screenresolutionforcamera.x=SCREENRESOLUTION.X;SCREENRESOLUTIONFORCAMERA.Y=SCREENRESOLUTION.Y; if(Screenresolution.x <screenresolution.y) {screenresolutionforcamera.x=SCREENRESOLUTION.Y;SCREENRESOLUTIONFORCAMERA.Y=screenresolution.x;} And then the Cameraresolution=getcameraresolution (parameters, screenresolution); Change to Cameraresolution= getcameraresolution (parameters, Screenresolutionforcamera);

After the completion, in the scanning operation, this time the camera shot out of the preview interface is normal display, no longer have tensile deformation problem.

This allows the project to introduce a two-dimensional code module function that can be used.

Android Project Combat (28): zxing Two-dimensional code implementation and optimization

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.