Android二維碼講解(ZXing)


在Android平臺上主流還是用zxing庫,ZXing是一個開放源碼的,用Java實現的多種格式的1D/2D條碼圖像處理庫,可以實現使用手機的內置的攝像頭完成條形碼的掃描及解碼。
因此這裏主要講述如何利用zxing進行二維碼開發。生成和識別二維碼,以實用性爲主。

   首先需要在github下載開源庫,然後進行刪減保留我們所需要的功能。
    下面現對用到的類進行一個簡單的介紹:
    ZXing庫裏面主要的類以及這些類的作用:
  • CaptureActivity             這個是啓動Activity 也就是掃描器。其中有個重要的方法是handleDecode()是對掃描結果處理。
  • decoding                      解碼相關的類。
  • encoding                      編碼相關的類。
  • camera                        包,攝像頭控制包。
  • View                            掃描取景類的包。

將減少過後的工程導入eclipse中或者android studio中
   實現一個掃描生成圖片的過程,
   這個主要依賴CaptureActivity這個類,這個類中比較重要的方法是handleDecode()。用Intent調用返回一個掃描成功的結果。
   
   一個實現輸入字符串生成二維碼圖片的功能。
   這個過程主要依賴EncodingHandler這個類中的createQRCode()方法。根據二維碼的算法生成一個bitmap圖片。


關於實際開發中可能遇到的問題(定製你所需要的二維碼掃描界面)
  • 上面的代碼還是比較簡單,但是要想做出像微信那樣只的掃描框,緊緊上面的代碼是沒有那種效果的,我們必須重寫com.mining.app.zxing.view包下面的ViewfinderView類,微信裏面的都是用的圖片,我是自己畫出來的,代碼註釋的比較清楚,大家直接看代碼吧,相信你能理解的,如果你要修改掃描框的大小,去CameraManager類裏面修改
  • public Rect getFramingRect() { 
  •   Point screenResolution = configManager.getScreenResolution();
  •   if (framingRect == null) {
  •    if (camera == null) {
  •     return null;
  •    }
  •    // 寬度
  •    // int width = screenResolution.x * 3 / 4;
  •    // if (width < MIN_FRAME_WIDTH) {
  •    // width = MIN_FRAME_WIDTH;
  •    // } else if (width > MAX_FRAME_WIDTH) {
  •    // width = MAX_FRAME_WIDTH;
  •    // }
  •    
  •    //高度
  •             // int height = screenResolution.y * 3 / 4;
  •             //if (height < MIN_FRAME_HEIGHT) {
  •             //height = MIN_FRAME_HEIGHT;
  •             //} else if (height > MAX_FRAME_HEIGHT) {
  •             //height = MAX_FRAME_HEIGHT;
  •             //}
  •    
  •    //寬高修改如下:
  •    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
  •    int width = (int) (metrics.widthPixels * 0.6);
  •    int height = (int) (width * 0.9);
  •    
  •    
  •    //這裏是左邊和上邊的偏移量
  •    int leftOffset = (screenResolution.x - width) / 2;
  •    //int topOffset = (screenResolution.y - height) / 2;
  •    
  •    //屏幕距離上邊的偏移量修改:
  •    int topOffset=(screenResolution.y - height)/4;
  •    framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
  •      topOffset + height);
  •    Log.d(TAG, "Calculated framing rect: " + framingRect);
  •   }
  •   return framingRect;
  • 修改掃描框的界面如下:

  1. /* 
  2.  * Copyright (C) 2008 ZXing authors 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package com.mining.app.zxing.view;  
  18.   
  19. import java.util.Collection;  
  20. import java.util.HashSet;  
  21.   
  22. import android.content.Context;  
  23. import android.content.res.Resources;  
  24. import android.graphics.Bitmap;  
  25. import android.graphics.Canvas;  
  26. import android.graphics.Color;  
  27. import android.graphics.Paint;  
  28. import android.graphics.Rect;  
  29. import android.graphics.Typeface;  
  30. import android.util.AttributeSet;  
  31. import android.view.View;  
  32.   
  33. import com.example.qr_codescan.R;  
  34. import com.google.zxing.ResultPoint;  
  35. import com.mining.app.zxing.camera.CameraManager;  
  36.   
  37. /** 
  38.  * This view is overlaid on top of the camera preview. It adds the viewfinder 
  39.  * rectangle and partial transparency outside it, as well as the laser scanner 
  40.  * animation and result points. 
  41.  *  
  42.  */  
  43. public final class ViewfinderView extends View {  
  44.     private static final String TAG = "log";  
  45.     /** 
  46.      * 刷新界面的時間 
  47.      */  
  48.     private static final long ANIMATION_DELAY = 10L;  
  49.     private static final int OPAQUE = 0xFF;  
  50.   
  51.     /** 
  52.      * 四個綠色邊角對應的長度 
  53.      */  
  54.     private int ScreenRate;  
  55.       
  56.     /** 
  57.      * 四個綠色邊角對應的寬度 
  58.      */  
  59.     private static final int CORNER_WIDTH = 10;  
  60.     /** 
  61.      * 掃描框中的中間線的寬度 
  62.      */  
  63.     private static final int MIDDLE_LINE_WIDTH = 6;  
  64.       
  65.     /** 
  66.      * 掃描框中的中間線的與掃描框左右的間隙 
  67.      */  
  68.     private static final int MIDDLE_LINE_PADDING = 5;  
  69.       
  70.     /** 
  71.      * 中間那條線每次刷新移動的距離 
  72.      */  
  73.     private static final int SPEEN_DISTANCE = 5;  
  74.       
  75.     /** 
  76.      * 手機的屏幕密度 
  77.      */  
  78.     private static float density;  
  79.     /** 
  80.      * 字體大小 
  81.      */  
  82.     private static final int TEXT_SIZE = 16;  
  83.     /** 
  84.      * 字體距離掃描框下面的距離 
  85.      */  
  86.     private static final int TEXT_PADDING_TOP = 30;  
  87.       
  88.     /** 
  89.      * 畫筆對象的引用 
  90.      */  
  91.     private Paint paint;  
  92.       
  93.     /** 
  94.      * 中間滑動線的最頂端位置 
  95.      */  
  96.     private int slideTop;  
  97.       
  98.     /** 
  99.      * 中間滑動線的最底端位置 
  100.      */  
  101.     private int slideBottom;  
  102.       
  103.     private Bitmap resultBitmap;  
  104.     private final int maskColor;  
  105.     private final int resultColor;  
  106.       
  107.     private final int resultPointColor;  
  108.     private Collection<ResultPoint> possibleResultPoints;  
  109.     private Collection<ResultPoint> lastPossibleResultPoints;  
  110.   
  111.     boolean isFirst;  
  112.       
  113.     public ViewfinderView(Context context, AttributeSet attrs) {  
  114.         super(context, attrs);  
  115.           
  116.         density = context.getResources().getDisplayMetrics().density;  
  117.         //將像素轉換成dp  
  118.         ScreenRate = (int)(20 * density);  
  119.   
  120.         paint = new Paint();  
  121.         Resources resources = getResources();  
  122.         maskColor = resources.getColor(R.color.viewfinder_mask);  
  123.         resultColor = resources.getColor(R.color.result_view);  
  124.   
  125.         resultPointColor = resources.getColor(R.color.possible_result_points);  
  126.         possibleResultPoints = new HashSet<ResultPoint>(5);  
  127.     }  
  128.   
  129.     @Override  
  130.     public void onDraw(Canvas canvas) {  
  131.         //中間的掃描框,你要修改掃描框的大小,去CameraManager裏面修改  
  132.         Rect frame = CameraManager.get().getFramingRect();  
  133.         if (frame == null) {  
  134.             return;  
  135.         }  
  136.           
  137.         //初始化中間線滑動的最上邊和最下邊  
  138.         if(!isFirst){  
  139.             isFirst = true;  
  140.             slideTop = frame.top;  
  141.             slideBottom = frame.bottom;  
  142.         }  
  143.           
  144.         //獲取屏幕的寬和高  
  145.         int width = canvas.getWidth();  
  146.         int height = canvas.getHeight();  
  147.   
  148.         paint.setColor(resultBitmap != null ? resultColor : maskColor);  
  149.           
  150.         //畫出掃描框外面的陰影部分,共四個部分,掃描框的上面到屏幕上面,掃描框的下面到屏幕下面  
  151.         //掃描框的左邊面到屏幕左邊,掃描框的右邊到屏幕右邊  
  152.         canvas.drawRect(00, width, frame.top, paint);  
  153.         canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);  
  154.         canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,  
  155.                 paint);  
  156.         canvas.drawRect(0, frame.bottom + 1, width, height, paint);  
  157.           
  158.           
  159.   
  160.         if (resultBitmap != null) {  
  161.             // Draw the opaque result bitmap over the scanning rectangle  
  162.             paint.setAlpha(OPAQUE);  
  163.             canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);  
  164.         } else {  
  165.   
  166.             //畫掃描框邊上的角,總共8個部分  
  167.             paint.setColor(Color.GREEN);  
  168.             canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,  
  169.                     frame.top + CORNER_WIDTH, paint);  
  170.             canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top  
  171.                     + ScreenRate, paint);  
  172.             canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,  
  173.                     frame.top + CORNER_WIDTH, paint);  
  174.             canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top  
  175.                     + ScreenRate, paint);  
  176.             canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left  
  177.                     + ScreenRate, frame.bottom, paint);  
  178.             canvas.drawRect(frame.left, frame.bottom - ScreenRate,  
  179.                     frame.left + CORNER_WIDTH, frame.bottom, paint);  
  180.             canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,  
  181.                     frame.right, frame.bottom, paint);  
  182.             canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,  
  183.                     frame.right, frame.bottom, paint);  
  184.   
  185.               
  186.             //繪製中間的線,每次刷新界面,中間的線往下移動SPEEN_DISTANCE  
  187.             slideTop += SPEEN_DISTANCE;  
  188.             if(slideTop >= frame.bottom){  
  189.                 slideTop = frame.top;  
  190.             }  
  191.             canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);  
  192.               
  193.               
  194.             //畫掃描框下面的字  
  195.             paint.setColor(Color.WHITE);  
  196.             paint.setTextSize(TEXT_SIZE * density);  
  197.             paint.setAlpha(0x40);  
  198.             paint.setTypeface(Typeface.create("System", Typeface.BOLD));  
  199.             canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);  
  200.               
  201.               
  202.   
  203.             Collection<ResultPoint> currentPossible = possibleResultPoints;  
  204.             Collection<ResultPoint> currentLast = lastPossibleResultPoints;  
  205.             if (currentPossible.isEmpty()) {  
  206.                 lastPossibleResultPoints = null;  
  207.             } else {  
  208.                 possibleResultPoints = new HashSet<ResultPoint>(5);  
  209.                 lastPossibleResultPoints = currentPossible;  
  210.                 paint.setAlpha(OPAQUE);  
  211.                 paint.setColor(resultPointColor);  
  212.                 for (ResultPoint point : currentPossible) {  
  213.                     canvas.drawCircle(frame.left + point.getX(), frame.top  
  214.                             + point.getY(), 6.0f, paint);  
  215.                 }  
  216.             }  
  217.             if (currentLast != null) {  
  218.                 paint.setAlpha(OPAQUE / 2);  
  219.                 paint.setColor(resultPointColor);  
  220.                 for (ResultPoint point : currentLast) {  
  221.                     canvas.drawCircle(frame.left + point.getX(), frame.top  
  222.                             + point.getY(), 3.0f, paint);  
  223.                 }  
  224.             }  
  225.   
  226.               
  227.             //只刷新掃描框的內容,其他地方不刷新  
  228.             postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,  
  229.                     frame.right, frame.bottom);  
  230.               
  231.         }  
  232.     }  
  233.   
  234.     public void drawViewfinder() {  
  235.         resultBitmap = null;  
  236.         invalidate();  
  237.     }  
  238.   
  239.     /** 
  240.      * Draw a bitmap with the result points highlighted instead of the live 
  241.      * scanning display. 
  242.      *  
  243.      * @param barcode 
  244.      *            An image of the decoded barcode. 
  245.      */  
  246.     public void drawResultBitmap(Bitmap barcode) {  
  247.         resultBitmap = barcode;  
  248.         invalidate();  
  249.     }  
  250.   
  251.     public void addPossibleResultPoint(ResultPoint point) {  
  252.         possibleResultPoints.add(point);  
  253.     }  
  254.   
  255. }  

中間畫的線:

  1. canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);  

改成

  1. Rect lineRect = new Rect();  
  2.             lineRect.left = frame.left;  
  3.             lineRect.right = frame.right;  
  4.             lineRect.top = slideTop;  
  5.             lineRect.bottom = slideTop + 18;  
  6.             canvas.drawBitmap(((BitmapDrawable)(getResources().getDrawable(R.drawable.qrcode_scan_line))).getBitmap(), null, lineRect, paint);  
  
    

   


   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章