[Unity+Android]横版扫描二维码

原地址:http://blog.csdn.net/dingxiaowei2013/article/details/25086835

终于解决了一个忧伤好久的问题,严重拖了项目进度,深感惭愧!一直被一系列的问题所困扰,然后又只能自己一个人摸索,也是一段辛酸忧伤史,现在小结一下上个月在做二维码的过程中所碰到的问题以及解决办法,现在庆幸终于解决好了,终于能将这个功能告一段落,一下小结也是分享一下Unity的某些“坑”,让同行少走弯路,起码在二维码这方面应该会有所启迪,欣慰的是接下来几天终于可以做自己应该做的事情了!

效果图:

先小结一下碰到的问题:

1.Unity工程屏幕方向与Android的工程屏幕方向要一致的问题

本来我测试Android扫码的功能,已经测是通过了,可以参考之前写的博文:http://blog.csdn.net/dingxiaowei2013/article/details/24677795,后来将这这个插件添加到现有的项目中,但导出项目apk后,打开应用怎么就是闪退,表示很忧伤,后来一步一步的精简对比测试,表示自己五一那天一直摸索到凌晨三点才发现这一问题根源,有了这个基础才有接下来思路的转变。我的Android工程设置的屏幕旋转方向是portrait,但由于项目原因,Unity的导出方向必须是landscapeleft,这两者方向不一致会导致应用异常奔溃闪退!当然我的解决思路可能是比较笨的,我将Android工程做成的插件的屏幕方向也做成了横屏的,为了和Unity的方向一致,我想应该就不会出现那种问题。我原本的思路是将Unity导出屏幕设置成auto,然后代码控制屏幕的方向,但貌似还是不成功,没辙只能还是换种思路!网上有不少Android的扫码工程,最多的就是基于zxing,但是都是有很多冗余,不适合初学者,尤其是像我这种Android初学者,我倒是看到一个比较适合入门的精简的扫码工程,可惜是纵屏的,上一篇文章就是介绍的这个,但并不适合我的项目需求,所以我就想办法将这个工程改成横屏工程,本以为只要改改xml配置文件就OK的,结果并不是想象的那么简单,仅仅那么该会出现扫的过程中图片压缩以及移动别扭等现象,还是需要修改里面的工程的!这里可以参考:http://dingxiaowei2013.blog.163.com/blog/static/21965310720144595534507/,这篇是将横屏改纵屏的解决方案,然后将其逆序操作,但我还是出现了一些问题,比如扫到一半的时候应用异常崩溃,又表示很忧伤,为啥都不是一帆风顺呢!然后反复重做,终于成功了!精简版的工程源码我会贴出来共享!为了实现这个功能,可谓是一次有一次的导出,一次有一次的测试,千言万语无法言表其中的忧伤,总而言之,坚韧,是程序猿必须具备的品质!

2.Unity与Android的场景跳转的问题

Unity和Android交互不仅仅是调用函数,交互数据,很大的一个还是需要交互视图和场景,将其很好的进行切换。当然场景的跳转或者是切换还是通过调用接口函数来实现,但这里通过了一个很重要的Activity来实现了这一效果,就是UnityPlayerActivity,Android的接口视图就是继承了这个UnityPlayerActivity,这个是为Unity和Android搭建了一个桥梁,当然这个类必须导入Unity的接口包,在Unity的安装目录下,详细可以参考上一篇文章,继承了UnityPlayerActivity的视图是作为Unity和Android的一个通用视图,它是Android插件的一个入口,无论是在Unity切换到Android界面还是Android切换到Unity界面,必须都要通过这个Activity来操作,记得是必须,这里我也是吃过苦头,我想在其他的Activity中来调用Unity的接口函数来实现Unity界面的跳转,但都尝试失败!后来再重头再来,这些都是经过了一遍又一遍的实验才得出的结论!

3.LG的手机作为统一的测试机貌似有一些问题(纯属个人感觉)

我测试最简单的OnGUI的方法,GUI里面包含中文,LG的显示不出来,由于公司所有的Android机和个人手机基本都是LG的,测试下来中文不显示,估计还得做字体,难道是因为它是韩国货?!纯属我个人瞎猜,解决办法就是你可以在工程里面做一套字体,然后做GUISkin供GUI用,我用其他的手机,比如我的破旧的中兴还有其他的非LG手机就能显示,这个横版的二维码扫码插件工程用LG测试还是有点问题,会出现扫的时候卡屏的现像,不知道是不是因为内存飙升,这个可以用Eclipse测试一下看看是不是因为这个原因!

4.Plugins文件夹必须放在Assets目录的下一级(切记)

我为了做成一个插件,所以就将所有的工程都拖放到一个目录下,结果发现界面的按钮点击不跳转到响应的AndroidActivity,然后知道Plugins必须要放在Assets目录下,估计引擎是根据这种关系来找对应的插件的!

附带修改的Andr​​oid的精简版的扫码工程代码(只贴修改过的脚本):

AndroidManifest.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.qr_codescan"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="16" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@android:style/Theme.NoTitleBar" >  
  16.            <activity  
  17.             android:name="com.example.qr_codescan.MainActivity"  
  18.             android:screenOrientation="landscape"  
  19.             android:label="@string/app_name" >  
  20.             <intent-filter>  
  21.                 <action android:name="android.intent.action.MAIN" />  
  22.   
  23.                 <category android:name="android.intent.category.LAUNCHER" />  
  24.             </intent-filter>  
  25.         </activity>  
  26.           
  27.         <activity  
  28.             android:name=".MipcaActivityCapture"  
  29.             android:configChanges="orientation|keyboardHidden"  
  30.             android:screenOrientation="landscape"  
  31.             android:windowSoftInputMode="stateAlwaysHidden" >  
  32.         </activity>  
  33.     </application>  
  34.   
  35.     <uses-permission android:name="android.permission.VIBRATE" />  
  36.     <uses-permission android:name="android.permission.CAMERA" />  
  37.       
  38.     <uses-feature android:name="android.hardware.camera" />  
  39.     <uses-feature android:name="android.hardware.camera.autofocus" />  
  40.   
  41. </manifest>  


MainActivity.java

  1. package com.example.qr_codescan;  
  2.   
  3.   
  4. import android.app.Activity;  
  5. import android.content.Intent;  
  6. import android.graphics.Bitmap;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.ImageView;  
  12. import android.widget.TextView;  
  13.   
  14. import com.unity3d.player.UnityPlayer;  
  15. import com.unity3d.player.UnityPlayerActivity;  
  16.   
  17. public class MainActivity extends UnityPlayerActivity {  
  18.     private final static int SCANNIN_GREQUEST_CODE = 1;  
  19.     /**  
  20.      * 显示扫描结果  
  21.      */  
  22. //  private TextView mTextView ;  
  23.     /**  
  24.      * 显示扫描拍的图片  
  25.      */  
  26. //  private ImageView mImageView;  
  27.       
  28.   
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32. //      setContentView(R.layout.activity_main);  
  33. //        
  34. //      mTextView = (TextView) findViewById(R.id.result);   
  35. //      mImageView = (ImageView) findViewById(R.id.qrcode_bitmap);  
  36. //        
  37. //      //点击按钮跳转到二维码扫描界面,这里用的是startActivityForResult跳转  
  38. //      //扫描完了之后调到该界面  
  39. //      Button mButton = (Button) findViewById(R.id.button1);  
  40. //      mButton.setOnClickListener(new OnClickListener() {  
  41. //            
  42. //          @Override  
  43. //          public void onClick(View v) {  
  44. //              Intent intent = new Intent();  
  45. //              intent.setClass(MainActivity.this, MipcaActivityCapture.class);  
  46. //              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  47. //              startActivityForResult(intent, SCANNIN_GREQUEST_CODE);  
  48. //          }  
  49. //      });  
  50.     }  
  51.       
  52.     public void Show()  
  53.     {  
  54.         Intent intent = new Intent();  
  55.         intent.setClass(MainActivity.this, MipcaActivityCapture.class);  
  56.         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  57.         startActivityForResult(intent, SCANNIN_GREQUEST_CODE);  
  58.     }  
  59.       
  60.       
  61.     @Override  
  62.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  63.         super.onActivityResult(requestCode, resultCode, data);  
  64.         switch (requestCode) {  
  65.         case SCANNIN_GREQUEST_CODE:  
  66.             if(resultCode == RESULT_OK){  
  67.                 Bundle bundle = data.getExtras();  
  68.                 //显示扫描到的内容  
  69. //              mTextView.setText(bundle.getString("result"));  
  70.                 //显示  
  71. //              mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));  
  72.                 UnityPlayer.UnitySendMessage("GameObject","GetString",bundle.getString("result"));  
  73.             }  
  74.             break;  
  75.         }  
  76.     }     
  77.   
  78. }  

MipcaActivityCapture.java

修改中文编码
字符集=“GBK”;

CameraConfigurationManager.java

  1. /*  
  2.  * Copyright (C) 2010 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.camera;  
  18.   
  19. import android.content.Context;  
  20. import android.graphics.Point;  
  21. import android.hardware.Camera;  
  22. import android.os.Build;  
  23. import android.util.Log;  
  24. import android.view.Display;  
  25. import android.view.WindowManager;  
  26.   
  27. import java.lang.reflect.Method;  
  28. import java.util.regex.Pattern;  
  29.   
  30. final class CameraConfigurationManager {  
  31.   
  32.   private static final String TAG = CameraConfigurationManager.class.getSimpleName();  
  33.   
  34.   private static final int TEN_DESIRED_ZOOM = 27;  
  35.   private static final int DESIRED_SHARPNESS = 30;  
  36.   
  37.   private static final Pattern COMMA_PATTERN = Pattern.compile(",");  
  38.   
  39.   private final Context context;  
  40.   private Point screenResolution;  
  41.   private Point cameraResolution;  
  42.   private int previewFormat;  
  43.   private String previewFormatString;  
  44.   
  45.   CameraConfigurationManager(Context context) {  
  46.     this.context = context;  
  47.   }  
  48.   
  49.   /**  
  50.    * Reads, one time, values from the camera that are needed by the app.  
  51.    */  
  52.   void initFromCameraParameters(Camera camera) {  
  53.     Camera.Parameters parameters = camera.getParameters();  
  54.     previewFormat = parameters.getPreviewFormat();  
  55.     previewFormatString = parameters.get("preview-format");  
  56.     Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);  
  57.     WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  
  58.     Display display = manager.getDefaultDisplay();  
  59.     screenResolution = new Point(display.getWidth(), display.getHeight());  
  60.     Log.d(TAG, "Screen resolution: " + screenResolution);  
  61.     cameraResolution = getCameraResolution(parameters, screenResolution);  
  62.     Log.d(TAG, "Camera resolution: " + screenResolution);  
  63.   }  
  64.   
  65.   /**  
  66.    * Sets the camera up to take preview images which are used for both preview and decoding.  
  67.    * We detect the preview format here so that buildLuminanceSource() can build an appropriate  
  68.    * LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,  
  69.    * and the planar Y can be used for barcode scanning without a copy in some cases.  
  70.    */  
  71.   void setDesiredCameraParameters(Camera camera) {  
  72.     Camera.Parameters parameters = camera.getParameters();  
  73.     Log.d(TAG, "Setting preview size: " + cameraResolution);  
  74.     parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);  
  75.     setFlash(parameters);  
  76.     setZoom(parameters);  
  77.     //setSharpness(parameters);  
  78.     //modify here  
  79.       
  80. //    camera.setDisplayOrientation(90);  
  81.     //兼容2.1  
  82.     //setDisplayOrientation(camera, 90);  
  83.     camera.setParameters(parameters);  
  84.   }  
  85.   
  86.   Point getCameraResolution() {  
  87.     return cameraResolution;  
  88.   }  
  89.   
  90.   Point getScreenResolution() {  
  91.     return screenResolution;  
  92.   }  
  93.   
  94.   int getPreviewFormat() {  
  95.     return previewFormat;  
  96.   }  
  97.   
  98.   String getPreviewFormatString() {  
  99.     return previewFormatString;  
  100.   }  
  101.   
  102.   private static Point getCameraResolution(Camera.Parameters parameters, Point screenResolution) {  
  103.   
  104.     String previewSizeValueString = parameters.get("preview-size-values");  
  105.     // saw this on Xperia  
  106.     if (previewSizeValueString == null) {  
  107.       previewSizeValueString = parameters.get("preview-size-value");  
  108.     }  
  109.   
  110.     Point cameraResolution = null;  
  111.   
  112.     if (previewSizeValueString != null) {  
  113.       Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString);  
  114.       cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);  
  115.     }  
  116.   
  117.     if (cameraResolution == null) {  
  118.       // Ensure that the camera resolution is a multiple of 8, as the screen may not be.  
  119.       cameraResolution = new Point(  
  120.           (screenResolution.x >> 3) << 3,  
  121.           (screenResolution.y >> 3) << 3);  
  122.     }  
  123.   
  124.     return cameraResolution;  
  125.   }  
  126.   
  127.   private static Point findBestPreviewSizeValue(CharSequence previewSizeValueString, Point screenResolution) {  
  128.     int bestX = 0;  
  129.     int bestY = 0;  
  130.     int diff = Integer.MAX_VALUE;  
  131.     for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {  
  132.   
  133.       previewSize = previewSize.trim();  
  134.       int dimPosition = previewSize.indexOf('x');  
  135.       if (dimPosition < 0) {  
  136.         Log.w(TAG, "Bad preview-size: " + previewSize);  
  137.         continue;  
  138.       }  
  139.   
  140.       int newX;  
  141.       int newY;  
  142.       try {  
  143.         newX = Integer.parseInt(previewSize.substring(0, dimPosition));  
  144.         newY = Integer.parseInt(previewSize.substring(dimPosition + 1));  
  145.       } catch (NumberFormatException nfe) {  
  146.         Log.w(TAG, "Bad preview-size: " + previewSize);  
  147.         continue;  
  148.       }  
  149.   
  150.       int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);  
  151.       if (newDiff == 0) {  
  152.         bestX = newX;  
  153.         bestY = newY;  
  154.         break;  
  155.       } else if (newDiff < diff) {  
  156.         bestX = newX;  
  157.         bestY = newY;  
  158.         diff = newDiff;  
  159.       }  
  160.   
  161.     }  
  162.   
  163.     if (bestX > 0 && bestY > 0) {  
  164.       return new Point(bestX, bestY);  
  165.     }  
  166.     return null;  
  167.   }  
  168.   
  169.   private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) {  
  170.     int tenBestValue = 0;  
  171.     for (String stringValue : COMMA_PATTERN.split(stringValues)) {  
  172.       stringValue = stringValue.trim();  
  173.       double value;  
  174.       try {  
  175.         value = Double.parseDouble(stringValue);  
  176.       } catch (NumberFormatException nfe) {  
  177.         return tenDesiredZoom;  
  178.       }  
  179.       int tenValue = (int) (10.0 * value);  
  180.       if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) {  
  181.         tenBestValue = tenValue;  
  182.       }  
  183.     }  
  184.     return tenBestValue;  
  185.   }  
  186.   
  187.   private void setFlash(Camera.Parameters parameters) {  
  188.     // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.  
  189.     // And this is a hack-hack to work around a different value on the Behold II  
  190.     // Restrict Behold II check to Cupcake, per Samsung's advice  
  191.     //if (Build.MODEL.contains("Behold II") &&  
  192.     //    CameraManager.SDK_INT == Build.VERSION_CODES.CUPCAKE) {  
  193.     if (Build.MODEL.contains("Behold II") && CameraManager.SDK_INT == 3) { // 3 = Cupcake  
  194.       parameters.set("flash-value", 1);  
  195.     } else {  
  196.       parameters.set("flash-value", 2);  
  197.     }  
  198.     // This is the standard setting to turn the flash off that all devices should honor.  
  199.     parameters.set("flash-mode", "off");  
  200.   }  
  201.   
  202.   private void setZoom(Camera.Parameters parameters) {  
  203.   
  204.     String zoomSupportedString = parameters.get("zoom-supported");  
  205.     if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) {  
  206.       return;  
  207.     }  
  208.   
  209.     int tenDesiredZoom = TEN_DESIRED_ZOOM;  
  210.   
  211.     String maxZoomString = parameters.get("max-zoom");  
  212.     if (maxZoomString != null) {  
  213.       try {  
  214.         int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString));  
  215.         if (tenDesiredZoom > tenMaxZoom) {  
  216.           tenDesiredZoom = tenMaxZoom;  
  217.         }  
  218.       } catch (NumberFormatException nfe) {  
  219.         Log.w(TAG, "Bad max-zoom: " + maxZoomString);  
  220.       }  
  221.     }  
  222.   
  223.     String takingPictureZoomMaxString = parameters.get("taking-picture-zoom-max");  
  224.     if (takingPictureZoomMaxString != null) {  
  225.       try {  
  226.         int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString);  
  227.         if (tenDesiredZoom > tenMaxZoom) {  
  228.           tenDesiredZoom = tenMaxZoom;  
  229.         }  
  230.       } catch (NumberFormatException nfe) {  
  231.         Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomMaxString);  
  232.       }  
  233.     }  
  234.   
  235.     String motZoomValuesString = parameters.get("mot-zoom-values");  
  236.     if (motZoomValuesString != null) {  
  237.       tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom);  
  238.     }  
  239.   
  240.     String motZoomStepString = parameters.get("mot-zoom-step");  
  241.     if (motZoomStepString != null) {  
  242.       try {  
  243.         double motZoomStep = Double.parseDouble(motZoomStepString.trim());  
  244.         int tenZoomStep = (int) (10.0 * motZoomStep);  
  245.         if (tenZoomStep > 1) {  
  246.           tenDesiredZoom -= tenDesiredZoom % tenZoomStep;  
  247.         }  
  248.       } catch (NumberFormatException nfe) {  
  249.         // continue  
  250.       }  
  251.     }  
  252.   
  253.     // Set zoom. This helps encourage the user to pull back.  
  254.     // Some devices like the Behold have a zoom parameter  
  255.     if (maxZoomString != null || motZoomValuesString != null) {  
  256.       parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));  
  257.     }  
  258.   
  259.     // Most devices, like the Hero, appear to expose this zoom parameter.  
  260.     // It takes on values like "27" which appears to mean 2.7x zoom  
  261.     if (takingPictureZoomMaxString != null) {  
  262.       parameters.set("taking-picture-zoom", tenDesiredZoom);  
  263.     }  
  264.   }  
  265.   
  266.     public static int getDesiredSharpness() {  
  267.         return DESIRED_SHARPNESS;  
  268.     }  
  269.       
  270.     /**  
  271.      * compatible  1.6  
  272.      * @param camera  
  273.      * @param angle  
  274.      */  
  275.     protected void setDisplayOrientation(Camera camera, int angle){    
  276.         Method downPolymorphic;    
  277.         try    
  278.         {    
  279.             downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });    
  280.             if (downPolymorphic != null)    
  281.                 downPolymorphic.invoke(camera, new Object[] { angle });    
  282.         }    
  283.         catch (Exception e1)    
  284.         {    
  285.         }    
  286.    }    
  287.   
  288. }  



CameraManager.java

  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.camera;  
  18.   
  19. import java.io.IOException;  
  20.   
  21. import android.content.Context;  
  22. import android.graphics.PixelFormat;  
  23. import android.graphics.Point;  
  24. import android.graphics.Rect;  
  25. import android.hardware.Camera;  
  26. import android.os.Build;  
  27. import android.os.Handler;  
  28. import android.util.Log;  
  29. import android.view.SurfaceHolder;  
  30.   
  31. /**  
  32.  * This object wraps the Camera service object and expects to be the only one talking to it. The  
  33.  * implementation encapsulates the steps needed to take preview-sized images, which are used for  
  34.  * both preview and decoding.  
  35.  *  
  36.  */  
  37. public final class CameraManager {  
  38.   
  39.   private static final String TAG = CameraManager.class.getSimpleName();  
  40.   
  41.   private static final int MIN_FRAME_WIDTH = 240;  
  42.   private static final int MIN_FRAME_HEIGHT = 240;  
  43.   private static final int MAX_FRAME_WIDTH = 480;  
  44.   private static final int MAX_FRAME_HEIGHT = 360;  
  45.   
  46.   private static CameraManager cameraManager;  
  47.   
  48.   static final int SDK_INT; // Later we can use Build.VERSION.SDK_INT  
  49.   static {  
  50.     int sdkInt;  
  51.     try {  
  52.       sdkInt = Integer.parseInt(Build.VERSION.SDK);  
  53.     } catch (NumberFormatException nfe) {  
  54.       // Just to be safe  
  55.       sdkInt = 10000;  
  56.     }  
  57.     SDK_INT = sdkInt;  
  58.   }  
  59.   
  60.   private final Context context;  
  61.   private final CameraConfigurationManager configManager;  
  62.   private Camera camera;  
  63.   private Rect framingRect;  
  64.   private Rect framingRectInPreview;  
  65.   private boolean initialized;  
  66.   private boolean previewing;  
  67.   private final boolean useOneShotPreviewCallback;  
  68.   /**  
  69.    * Preview frames are delivered here, which we pass on to the registered handler. Make sure to  
  70.    * clear the handler so it will only receive one message.  
  71.    */  
  72.   private final PreviewCallback previewCallback;  
  73.   /** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */  
  74.   private final AutoFocusCallback autoFocusCallback;  
  75.   
  76.   /**  
  77.    * Initializes this static object with the Context of the calling Activity.  
  78.    *  
  79.    * @param context The Activity which wants to use the camera.  
  80.    */  
  81.   public static void init(Context context) {  
  82.     if (cameraManager == null) {  
  83.       cameraManager = new CameraManager(context);  
  84.     }  
  85.   }  
  86.   
  87.   /**  
  88.    * Gets the CameraManager singleton instance.  
  89.    *  
  90.    * @return A reference to the CameraManager singleton.  
  91.    */  
  92.   public static CameraManager get() {  
  93.     return cameraManager;  
  94.   }  
  95.   
  96.   private CameraManager(Context context) {  
  97.   
  98.     this.context = context;  
  99.     this.configManager = new CameraConfigurationManager(context);  
  100.   
  101.     // Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older  
  102.     // Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use  
  103.     // the more efficient one shot callback, as the older one can swamp the system and cause it  
  104.     // to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.  
  105.     //useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;  
  106.     useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > 3; // 3 = Cupcake  
  107.   
  108.     previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);  
  109.     autoFocusCallback = new AutoFocusCallback();  
  110.   }  
  111.   
  112.   /**  
  113.    * Opens the camera driver and initializes the hardware parameters.  
  114.    *  
  115.    * @param holder The surface object which the camera will draw preview frames into.  
  116.    * @throws IOException Indicates the camera driver failed to open.  
  117.    */  
  118.   public void openDriver(SurfaceHolder holder) throws IOException {  
  119.     if (camera == null) {  
  120.       camera = Camera.open();  
  121.       if (camera == null) {  
  122.         throw new IOException();  
  123.       }  
  124.       camera.setPreviewDisplay(holder);  
  125.   
  126.       if (!initialized) {  
  127.         initialized = true;  
  128.         configManager.initFromCameraParameters(camera);  
  129.       }  
  130.       configManager.setDesiredCameraParameters(camera);  
  131.   
  132.       //FIXME  
  133.  //     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);  
  134.       //是否使用前灯  
  135. //      if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {  
  136. //        FlashlightManager.enableFlashlight();  
  137. //      }  
  138.       FlashlightManager.enableFlashlight();  
  139.     }  
  140.   }  
  141.   
  142.   /**  
  143.    * Closes the camera driver if still in use.  
  144.    */  
  145.   public void closeDriver() {  
  146.     if (camera != null) {  
  147.       FlashlightManager.disableFlashlight();  
  148.       camera.release();  
  149.       camera = null;  
  150.     }  
  151.   }  
  152.   
  153.   /**  
  154.    * Asks the camera hardware to begin drawing preview frames to the screen.  
  155.    */  
  156.   public void startPreview() {  
  157.     if (camera != null && !previewing) {  
  158.       camera.startPreview();  
  159.       previewing = true;  
  160.     }  
  161.   }  
  162.   
  163.   /**  
  164.    * Tells the camera to stop drawing preview frames.  
  165.    */  
  166.   public void stopPreview() {  
  167.     if (camera != null && previewing) {  
  168.       if (!useOneShotPreviewCallback) {  
  169.         camera.setPreviewCallback(null);  
  170.       }  
  171.       camera.stopPreview();  
  172.       previewCallback.setHandler(null, 0);  
  173.       autoFocusCallback.setHandler(null, 0);  
  174.       previewing = false;  
  175.     }  
  176.   }  
  177.   
  178.   /**  
  179.    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]  
  180.    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,  
  181.    * respectively.  
  182.    *  
  183.    * @param handler The handler to send the message to.  
  184.    * @param message The what field of the message to be sent.  
  185.    */  
  186.   public void requestPreviewFrame(Handler handler, int message) {  
  187.     if (camera != null && previewing) {  
  188.       previewCallback.setHandler(handler, message);  
  189.       if (useOneShotPreviewCallback) {  
  190.         camera.setOneShotPreviewCallback(previewCallback);  
  191.       } else {  
  192.         camera.setPreviewCallback(previewCallback);  
  193.       }  
  194.     }  
  195.   }  
  196.   
  197.   /**  
  198.    * Asks the camera hardware to perform an autofocus.  
  199.    *  
  200.    * @param handler The Handler to notify when the autofocus completes.  
  201.    * @param message The message to deliver.  
  202.    */  
  203.   public void requestAutoFocus(Handler handler, int message) {  
  204.     if (camera != null && previewing) {  
  205.       autoFocusCallback.setHandler(handler, message);  
  206.       //Log.d(TAG, "Requesting auto-focus callback");  
  207.       camera.autoFocus(autoFocusCallback);  
  208.     }  
  209.   }  
  210.   
  211.   /**  
  212.    * Calculates the framing rect which the UI should draw to show the user where to place the  
  213.    * barcode. This target helps with alignment as well as forces the user to hold the device  
  214.    * far enough away to ensure the image will be in focus.  
  215.    *  
  216.    * @return The rectangle to draw on screen in window coordinates.  
  217.    */  
  218.   public Rect getFramingRect() {  
  219.     Point screenResolution = configManager.getScreenResolution();  
  220.     if (framingRect == null) {  
  221.       if (camera == null) {  
  222.         return null;  
  223.       }  
  224.       int width = screenResolution.x * 3 / 4;  
  225.       if (width < MIN_FRAME_WIDTH) {  
  226.         width = MIN_FRAME_WIDTH;  
  227.       } else if (width > MAX_FRAME_WIDTH) {  
  228.         width = MAX_FRAME_WIDTH;  
  229.       }  
  230.       int height = screenResolution.y * 3 / 4;  
  231.       if (height < MIN_FRAME_HEIGHT) {  
  232.         height = MIN_FRAME_HEIGHT;  
  233.       } else if (height > MAX_FRAME_HEIGHT) {  
  234.         height = MAX_FRAME_HEIGHT;  
  235.       }  
  236.       int leftOffset = (screenResolution.x - width) / 2;  
  237.       int topOffset = (screenResolution.y - height) / 2;  
  238.       framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);  
  239.       Log.d(TAG, "Calculated framing rect: " + framingRect);  
  240.     }  
  241.     return framingRect;  
  242.   }  
  243.   
  244.   /**  
  245.    * Like {@link #getFramingRect} but coordinates are in terms of the preview frame,  
  246.    * not UI / screen.  
  247.    */  
  248.   public Rect getFramingRectInPreview() {  
  249.     if (framingRectInPreview == null) {  
  250.       Rect rect = new Rect(getFramingRect());  
  251.       Point cameraResolution = configManager.getCameraResolution();  
  252.       Point screenResolution = configManager.getScreenResolution();  
  253.       //modify here  
  254.       rect.left = rect.left * cameraResolution.x / screenResolution.x;  
  255.       rect.right = rect.right * cameraResolution.x / screenResolution.x;  
  256.       rect.top = rect.top * cameraResolution.y / screenResolution.y;  
  257.       rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;  
  258.       //rect.left = rect.left * cameraResolution.y / screenResolution.x;  
  259.       //rect.right = rect.right * cameraResolution.y / screenResolution.x;  
  260.       //rect.top = rect.top * cameraResolution.x / screenResolution.y;  
  261.       //rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;  
  262.       framingRectInPreview = rect;  
  263.     }  
  264.     return framingRectInPreview;  
  265.   }  
  266.   
  267.   /**  
  268.    * Converts the result points from still resolution coordinates to screen coordinates.  
  269.    *  
  270.    * @param points The points returned by the Reader subclass through Result.getResultPoints().  
  271.    * @return An array of Points scaled to the size of the framing rect and offset appropriately  
  272.    *         so they can be drawn in screen coordinates.  
  273.    */  
  274.   /*  
  275.   public Point[] convertResultPoints(ResultPoint[] points) {  
  276.     Rect frame = getFramingRectInPreview();  
  277.     int count = points.length;  
  278.     Point[] output = new Point[count];  
  279.     for (int x = 0; x < count; x++) {  
  280.       output[x] = new Point();  
  281.       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);  
  282.       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);  
  283.     }  
  284.     return output;  
  285.   }  
  286.    */  
  287.   
  288.   /**  
  289.    * A factory method to build the appropriate LuminanceSource object based on the format  
  290.    * of the preview buffers, as described by Camera.Parameters.  
  291.    *  
  292.    * @param data A preview frame.  
  293.    * @param width The width of the image.  
  294.    * @param height The height of the image.  
  295.    * @return A PlanarYUVLuminanceSource instance.  
  296.    */  
  297.   public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {  
  298.     Rect rect = getFramingRectInPreview();  
  299.     int previewFormat = configManager.getPreviewFormat();  
  300.     String previewFormatString = configManager.getPreviewFormatString();  
  301.     switch (previewFormat) {  
  302.       // This is the standard Android format which all devices are REQUIRED to support.  
  303.       // In theory, it's the only one we should ever care about.  
  304.       case PixelFormat.YCbCr_420_SP:  
  305.       // This format has never been seen in the wild, but is compatible as we only care  
  306.       // about the Y channel, so allow it.  
  307.       case PixelFormat.YCbCr_422_SP:  
  308.         return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,  
  309.             rect.width(), rect.height());  
  310.       default:  
  311.         // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.  
  312.         // Fortunately, it too has all the Y data up front, so we can read it.  
  313.         if ("yuv420p".equals(previewFormatString)) {  
  314.           return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,  
  315.             rect.width(), rect.height());  
  316.         }  
  317.     }  
  318.     throw new IllegalArgumentException("Unsupported picture format: " +  
  319.         previewFormat + '/' + previewFormatString);  
  320.   }  
  321.   
  322.     public Context getContext() {  
  323.         return context;  
  324.     }  
  325.   
  326. }  



PlanarYUVLuminanceSource.java

  1. /*  
  2.  * Copyright 2009 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.camera;  
  18.   
  19. import com.google.zxing.LuminanceSource;  
  20.   
  21. import android.graphics.Bitmap;  
  22.   
  23. /**  
  24.  * This object extends LuminanceSource around an array of YUV data returned from the camera driver,  
  25.  * with the option to crop to a rectangle within the full data. This can be used to exclude  
  26.  * superfluous pixels around the perimeter and speed up decoding.  
  27.  *  
  28.  * It works for any pixel format where the Y channel is planar and appears first, including  
  29.  * YCbCr_420_SP and YCbCr_422_SP.  
  30.  *  
  31.  * @author dswitkin@google.com (Daniel Switkin)  
  32.  */  
  33. public final class PlanarYUVLuminanceSource extends LuminanceSource {  
  34.   private final byte[] yuvData;  
  35.   private final int dataWidth;  
  36.   private final int dataHeight;  
  37.   private final int left;  
  38.   private final int top;  
  39.   
  40.   public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top,  
  41.       int width, int height) {  
  42.     super(width, height);  
  43.   
  44.     if (left + width > dataWidth || top + height > dataHeight) {  
  45.       throw new IllegalArgumentException("Crop rectangle does not fit within image data.");  
  46.     }  
  47.   
  48.     this.yuvData = yuvData;  
  49.     this.dataWidth = dataWidth;  
  50.     this.dataHeight = dataHeight;  
  51.     this.left = left;  
  52.     this.top = top;  
  53.   }  
  54.   
  55.   @Override  
  56.   public byte[] getRow(int y, byte[] row) {  
  57.     if (y < 0 || y >= getHeight()) {  
  58.       throw new IllegalArgumentException("Requested row is outside the image: " + y);  
  59.     }  
  60.     int width = getWidth();  
  61.     if (row == null || row.length < width) {  
  62.       row = new byte[width];  
  63.     }  
  64.     int offset = (y + top) * dataWidth + left;  
  65.     System.arraycopy(yuvData, offset, row, 0, width);  
  66.     return row;  
  67.   }  
  68.   
  69.   @Override  
  70.   public byte[] getMatrix() {  
  71.     int width = getWidth();  
  72.     int height = getHeight();  
  73.   
  74.     // If the caller asks for the entire underlying image, save the copy and give them the  
  75.     // original data. The docs specifically warn that result.length must be ignored.  
  76.     if (width == dataWidth && height == dataHeight) {  
  77.       return yuvData;  
  78.     }  
  79.   
  80.     int area = width * height;  
  81.     byte[] matrix = new byte[area];  
  82.     int inputOffset = top * dataWidth + left;  
  83.   
  84.     // If the width matches the full width of the underlying data, perform a single copy.  
  85.     if (width == dataWidth) {  
  86.       System.arraycopy(yuvData, inputOffset, matrix, 0, area);  
  87.       return matrix;  
  88.     }  
  89.   
  90.     // Otherwise copy one cropped row at a time.  
  91.     byte[] yuv = yuvData;  
  92.     for (int y = 0; y < height; y++) {  
  93.       int outputOffset = y * width;  
  94.       System.arraycopy(yuv, inputOffset, matrix, outputOffset, width);  
  95.       inputOffset += dataWidth;  
  96.     }  
  97.     return matrix;  
  98.   }  
  99.   
  100.   @Override  
  101.   public boolean isCropSupported() {  
  102.     return true;  
  103.   }  
  104.   
  105.   public int getDataWidth() {  
  106.     return dataWidth;  
  107.   }  
  108.   
  109.   public int getDataHeight() {  
  110.     return dataHeight;  
  111.   }  
  112.   
  113.   public Bitmap renderCroppedGreyscaleBitmap() {  
  114.     int width = getWidth();  
  115.     int height = getHeight();  
  116.     int[] pixels = new int[width * height];  
  117.     byte[] yuv = yuvData;  
  118.     int inputOffset = top * dataWidth + left;  
  119.   
  120.     for (int y = 0; y < height; y++) {  
  121.       int outputOffset = y * width;  
  122.       for (int x = 0; x < width; x++) {  
  123.         int grey = yuv[inputOffset + x] & 0xff;  
  124.         pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);  
  125.       }  
  126.       inputOffset += dataWidth;  
  127.     }  
  128.   
  129.     Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);  
  130.     bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
  131.     return bitmap;  
  132.   }  
  133. }  



能解决这一系列的问题还要感觉龙哥的指导,在此感谢!
这时比较晚了就不贴原工程了,明天贴出来!
 
如果有谁知道以上问题有更好的解决方案,还望指教,相互学习,Aladdin在此感谢,哈哈!
我的微博:http://weibo.com/dingxiaowei2013
 
工程源码:http://down.51cto.com/data/1164585
原文地址:https://www.cnblogs.com/123ing/p/3851193.html