android入門:zxing學習筆記(二)

 上一篇介紹了zxing掃描二維碼的過程,剛開始看這份代碼時,不怎麼明白,很多細節都不清楚,到後來又了更深的理解後,發現這代碼設計的就是好,質量高。整個掃描二維碼和一維碼的過程是非常迅速的,效率很高。最近發現微博上有個二維坊的ID,發得qr碼圖形都非常的Q,不知道怎麼弄出來的,程序員可以借這個可愛的qr碼浪漫下。

     在整個zxing的android代碼部分,很重要的兩點是main activity 和 camera。在這一篇,就主要介紹下android camera的使用。打開zxing下的Barcode scanner,並會有如下的界面。爲了更好的理解camera,先介紹這個界面。

Barcode Scanner的界面

    剛開始接觸到android時,對此界面一點不熟悉。後面認真看了其中的代碼,明白了一點點。 這個界面的定義主要在ViewfinderView.java這個類中,這個類繼承了View類,實現了自定義的View。View就是對應於屏幕的一個畫布,可以在這個屏幕上任意繪製你想要的設計。最重要的重載onDraw函數,在其中實現繪製。就來看下ViewfinderView是如何實現界面上的感覺的。

    畫面中一共分爲兩塊:外邊半透明的一片,中間全透明的一片。外面半透明的畫面是由四個矩形組成。

1 paint.setColor(resultBitmap != null ? resultColor : maskColor);
2 canvas.drawRect(0, 0, width, frame.top, paint);
3 canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
4 canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
5 canvas.drawRect(0, frame.bottom + 1, width, height, paint);

    drawRect函數有五個參數,前四個參數構成兩個座標,組成一個矩形,後面一個畫筆相關的。

   中間的全透明一塊,也是由四個矩形組成,只是每個矩形很窄,才一兩個像素,成了一條直線。

1 paint.setColor(frameColor);
2 canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
3 canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
4 canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
5 canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);

   最中間的一條紅色掃描線亦如此。

   onDraw()函數的最後一句是:

1 postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom);

    這一句很關鍵,postInvalidateDelayed函數主要用來在非UI線程中刷新UI界面,每個ANIMATION_DELAY時間,刷新指定的範圍。所以會不停得調用onDraw函數,並在界面上添加綠色的特徵點。在剛開始看這份代碼時,沒明白是如何添加綠色的標記點的。現在再看了一遍,大致明白了。在camera聚焦穫取圖片後,再使用core中的庫進行解析,會得出特徵點的座標,最後通過ViewfinderResultPointCallback類回調,將特徵點添加到ViewfinderView中的ArrayList容器中。

1 public void foundPossibleResultPoint(ResultPoint point) {
2 viewfinderView.addPossibleResultPoint(point);
3 }

    這個函數特徵點加入到possibleResultPoints中,由於對java不熟悉,不知道 “=” 的賦值對於List來說是淺拷貝,總在想possibleResultPoints對象沒有被賦值,如何獲取這些特徵點了。後面才知道,這個“=”賦值,只是個淺拷貝。若要對這種預定義的集合實現深拷貝,可以使用構造函數,

如:List<ResultPoint> points = new List<ResultPoint>(possibleResultPoints);

複製代碼
 1   public void addPossibleResultPoint(ResultPoint point) {
2 List<ResultPoint> points = possibleResultPoints;
3 synchronized (point) {
4 points.add(point);
5 int size = points.size();
6 if (size > MAX_RESULT_POINTS) {
7 // trim it
8 points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
9 }
10 }
11 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章