最近项目条码扫描要改为横屏,网上所搜了一下,然后修改下面写代码就可以实现横屏条码扫描了
修改前效果图如下
具体代码修改如下:
1修改 activity配置文件
<activity
android:name=".CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden" >
</activity>
android:screenOrientation="portrait" 是关键 默认是landscape
2修改CameraManager.java的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;
3 修改CameraConfigurationManag
在setZoom(parameters);后增加setDisplayOrientation(camera, 180); 在setDesiredCameraParamete
private void setDisplayOrientation(Camera camera, int angle) {
Method downPolymorphic;
try {
downPolymorphic = camera.getClass().getMethod(
“setDisplayOrientation”, new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
} catch (Exception e1) {
}
}
4
修改DecodeHandler.java中的decode函数,
将PlanarYUVLuminanceSource
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; // Here we are swapping, that’s the difference to #11
width = height;
height = tmp;
PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(rotatedData, width, height)
5 到此问题已经解决,非常好,只是有一个问题:兼容性
如果是ZXing的版本是1.7的,对于之前的版本来讲当手机扫描时,手机描绘的可能点与实际有偏差,所以需要修改ViewfinderView.java的onDraw函数,在Collection<ResultPoint> currentPossible = possibleResultPoints;前增加
Rect previewFrame = CameraManager.get().getFramingRectInPreview();
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
将本函数中下边的两个for语句中的canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint);
修改为canvas.drawCircle(frame.left
+
(int)
(point.getX()
*
scaleX),
frame.top
+
(int)
(point.getY()
*
scaleY),
3.0f,
paint);
注意,是修改两个位置的for语句。
如果您还想将扫描的框变大一些,请修改CameraManager.java中的getFramingRect函数,
将framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);修改为framingRect = new Rect(0, topOffset, leftOffset * 2 + width, topOffset + height);这种修改方法会将扫描框的左右两边与屏幕相平。
但是黑色的边框对于用户好像也不太好辨认,所以我又修改了边框的颜色,将ViewfinderView.java文件中的paint.setColor(frameColor);修改为paint.setColor(laserColor);,这样就修改成了与扫描中间的一样的颜色
修改后效果图如下: