個人網站:臭蛋 www.choudan.net
上一篇介紹了zxing掃描二維碼的過程,剛開始看這份代碼時,不怎么明白,很多細節都不清楚,到后來又了更深的理解后,發現這代碼設計的就是好,質量高。整個掃描二維碼和一維碼的過程是非常迅速的,效率很高。最近發現微博上有個二維坊的ID,發得qr碼圖形都非常的Q,不知道怎么弄出來的,程序員可以借這個可愛的qr碼浪漫下。
在整個zxing的android代碼部分,很重要的兩點是main activity 和 camera。在這一篇,就主要介紹下android camera的使用。打開zxing下的Barcode scanner,並會有如下的界面。為了更好的理解camera,先介紹這個界面。
剛開始接觸到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 }
如果想深入的查看view刷新的過程,具體實現,查看下面這個鏈接,這個系列文章寫的很詳細。
AndroidBluetooth博客:View編程(2): invalidate()再探