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

时间:2021-07-12 23:30:32

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

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

效果图:

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

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

先小结一下碰到的问题:

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. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="16" />
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@android:style/Theme.NoTitleBar" >
  14. <activity
  15. android:name="com.example.qr_codescan.MainActivity"
  16. android:screenOrientation="landscape"
  17. android:label="@string/app_name" >
  18. <intent-filter>
  19. <action android:name="android.intent.action.MAIN" />
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. <activity
  24. android:name=".MipcaActivityCapture"
  25. android:configChanges="orientation|keyboardHidden"
  26. android:screenOrientation="landscape"
  27. android:windowSoftInputMode="stateAlwaysHidden" >
  28. </activity>
  29. </application>
  30. <uses-permission android:name="android.permission.VIBRATE" />
  31. <uses-permission android:name="android.permission.CAMERA" />
  32. <uses-feature android:name="android.hardware.camera" />
  33. <uses-feature android:name="android.hardware.camera.autofocus" />
  34. </manifest>

MainActivity.java

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

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

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

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. package com.mining.app.zxing.camera;
  17. import com.google.zxing.LuminanceSource;
  18. import android.graphics.Bitmap;
  19. /**
  20. * This object extends LuminanceSource around an array of YUV data returned from the camera driver,
  21. * with the option to crop to a rectangle within the full data. This can be used to exclude
  22. * superfluous pixels around the perimeter and speed up decoding.
  23. *
  24. * It works for any pixel format where the Y channel is planar and appears first, including
  25. * YCbCr_420_SP and YCbCr_422_SP.
  26. *
  27. * @author dswitkin@google.com (Daniel Switkin)
  28. */
  29. public final class PlanarYUVLuminanceSource extends LuminanceSource {
  30. private final byte[] yuvData;
  31. private final int dataWidth;
  32. private final int dataHeight;
  33. private final int left;
  34. private final int top;
  35. public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top,
  36. int width, int height) {
  37. super(width, height);
  38. if (left + width > dataWidth || top + height > dataHeight) {
  39. throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
  40. }
  41. this.yuvData = yuvData;
  42. this.dataWidth = dataWidth;
  43. this.dataHeight = dataHeight;
  44. this.left = left;
  45. this.top = top;
  46. }
  47. @Override
  48. public byte[] getRow(int y, byte[] row) {
  49. if (y < 0 || y >= getHeight()) {
  50. throw new IllegalArgumentException("Requested row is outside the image: " + y);
  51. }
  52. int width = getWidth();
  53. if (row == null || row.length < width) {
  54. row = new byte[width];
  55. }
  56. int offset = (y + top) * dataWidth + left;
  57. System.arraycopy(yuvData, offset, row, 0, width);
  58. return row;
  59. }
  60. @Override
  61. public byte[] getMatrix() {
  62. int width = getWidth();
  63. int height = getHeight();
  64. // If the caller asks for the entire underlying image, save the copy and give them the
  65. // original data. The docs specifically warn that result.length must be ignored.
  66. if (width == dataWidth && height == dataHeight) {
  67. return yuvData;
  68. }
  69. int area = width * height;
  70. byte[] matrix = new byte[area];
  71. int inputOffset = top * dataWidth + left;
  72. // If the width matches the full width of the underlying data, perform a single copy.
  73. if (width == dataWidth) {
  74. System.arraycopy(yuvData, inputOffset, matrix, 0, area);
  75. return matrix;
  76. }
  77. // Otherwise copy one cropped row at a time.
  78. byte[] yuv = yuvData;
  79. for (int y = 0; y < height; y++) {
  80. int outputOffset = y * width;
  81. System.arraycopy(yuv, inputOffset, matrix, outputOffset, width);
  82. inputOffset += dataWidth;
  83. }
  84. return matrix;
  85. }
  86. @Override
  87. public boolean isCropSupported() {
  88. return true;
  89. }
  90. public int getDataWidth() {
  91. return dataWidth;
  92. }
  93. public int getDataHeight() {
  94. return dataHeight;
  95. }
  96. public Bitmap renderCroppedGreyscaleBitmap() {
  97. int width = getWidth();
  98. int height = getHeight();
  99. int[] pixels = new int[width * height];
  100. byte[] yuv = yuvData;
  101. int inputOffset = top * dataWidth + left;
  102. for (int y = 0; y < height; y++) {
  103. int outputOffset = y * width;
  104. for (int x = 0; x < width; x++) {
  105. int grey = yuv[inputOffset + x] & 0xff;
  106. pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
  107. }
  108. inputOffset += dataWidth;
  109. }
  110. Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  111. bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
  112. return bitmap;
  113. }
  114. }
能解决这一系列的问题还要感觉龙哥的指导,在此感谢!
这时比较晚了就不贴原工程了,明天贴出来!
 
如果有谁知道以上问题有更好的解决方案,还望指教,相互学习,Aladdin在此感谢,哈哈!
我的微博:http://weibo.com/dingxiaowei2013
 
工程源码:http://down.51cto.com/data/1164585