转载请注明出处,http://blog.csdn.net/Bule_Zst/article/details/74450685
在“使用zxing实现二维码的扫描功能”一文中已经完成了基本的扫描功能,但是是横屏的,这篇文章主要介绍了如何修改项目,实现竖屏扫描功能。
找到CameraConfigurationManager类,类的位置为:com.google.zxing.client.android.camera;
- 替换initFromCameraParameters方法
void initFromCameraParameters(OpenCamera camera) {
Camera.Parameters parameters = camera.getCamera().getParameters();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point theScreenResolution = new Point();
display.getSize(theScreenResolution);
screenResolution = theScreenResolution;
Log.i(TAG, "Screen resolution: " + screenResolution);
//修改竖屏显示,解决图形拉伸问题
Point p = new Point();
p.x = this.screenResolution.x;
p.y = this.screenResolution.y;
if (this.screenResolution.x < this.screenResolution.y) {
p.x = this.screenResolution.y;
p.y = this.screenResolution.x;
}
cameraResolution = CameraConfigurationUtils.findBestPreviewSizeValue(parameters, p);
Log.i(TAG, "Camera resolution: " + cameraResolution);
}
- 修改setDesiredCameraParameters方法
在Camera theCamera = camera.getCamera();
后添加代码
theCamera.setDisplayOrientation( 90 );
替换CameraManager类中的getFramingRectInPreview方法,类的位置:com.google.zxing.client.android.camera;
public synchronized Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect framingRect = getFramingRect();
if (framingRect == null) {
return null;
}
Rect rect = new Rect(framingRect);
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
if (cameraResolution == null || screenResolution == null) {
// Called early, before init even finished
return null;
}
//修改竖屏,扫描框尺寸的变换
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);
framingRectInPreview = rect;
}
return framingRectInPreview;
}
修改DecodeHandler类中的decode方法,类的位置:com.google.zxing.client.android;
在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 temp = width;
width = height;
height = temp;
data = rotatedData;
将AndroidManifest主配置文件的CaptureActivity显示改为竖屏显示
android:screenOrientation="portrait"
原本是android:screenOrientation="landscape"
在CaptureActivity类中将onResume方法里的下面这段代码注释掉,类的位置:com.google.zxing.client.android;
if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_AUTO_ORIENTATION, true)) {
setRequestedOrientation(getCurrentOrientation());
} else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
resetStatusView();