原博地址:http://www.open-open.com/lib/view/open1437533499553.html
zxing如何竖屏扫描
将zxing源码android导入Eclipse后,关联ZXLib,也就是刚才新建的ZXing类库。运行后可直接使用条码扫描功能,可是默认是横屏,笔者项目中需要使用竖屏方式扫描,于是需要将zxing条码扫描改成竖屏方式扫描。步骤写的有些细致,请耐心阅读。第一步:修改AndroidManifest工程清单,AndroidManifest中CaptureActivity的screenOrientation属性改为portrait:
<activity android:name=".CaptureActivity"
android:screenOrientation="portrait"
android:clearTaskOnLaunch="true"
android:stateNotNeeded="true"
android:theme="@style/CaptureTheme"
android:windowSoftInputMode="stateAlwaysHidden">
第二步:删除CaptureActivity中把onResume方法中的无用代码:
// if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_AUTO_ORIENTATION, true)) {
// setRequestedOrientation(getCurrentOrientation());
// } else {
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
// }
第三步:在CaptureActivity中把onCreate方法结尾处添加代码:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
经过前三步,条码扫描器已经竖屏了,相信很多人也改到这里就出现问题了,zxing条码扫描器相机预览方向旋转了90度,并且容易拉伸,我们需要纠正相机预览方向
第四步:在CameraConfigurationManager的setDesiredCameraParameters方法中添加代码:
在 camera.setParameters(parameters); 前
加: setDisplayOrientation(camera, 90);
相机预览正常了,也没有拉伸,可是二维码识别却慢了许多,并且一维条码识别不出来,需要横屏扫描才可以识别,而且条码成像仍然是横向的,下面步骤将解决这个问题。
第五步:修改CameraManager中getFramingRectInPreview方法:
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
第六步:修改DecodeHandler中的decode(byte[] data, int width, int height)方法:
在 PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height);前添加
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width;
width = height;
height = tmp;
data = rotatedData;
完成上面六步已经基本可是实现 竖屏,可能还不灵敏,需要调整ViewfinderView 和SurfaceView 的大小,灵敏度越高