大家好,stackoverflow 的人,作为一个对应用程序开发知识很少的 EE 学生,我被分配了为我的研究小组“修复”一个未完成的应用程序的任务。我的第一个任务是实现一个切换按钮,将相机从前翻转到后。我有一些想法,但我不确定如何使用旧的应用程序代码来实现它们。
我想创建一个切换按钮侦听器,并使用此侦听器来决定使用哪个摄像头。目前,我正在查看这部分代码...
public void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "opening camera");
try {
String cameraId = manager.getCameraIdList()[1];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
assert map != null;
//imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
imageDimension = new Size(1280, 960);
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
showToast("Please grant permissions before starting the service.");
} else {
manager.openCamera(cameraId, stateCallback, null);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
我的想法是,我可以在 openCamera 类中创建一个条件语句,检查切换按钮是打开还是关闭,然后打开正确的摄像头(在前置摄像头时,在后置摄像头时关闭)。同样,我对应用程序开发完全陌生,所以如果这是一个不正确的解决方案,请通知我。
回答1
我做了一些研究,我在网上找到了一些这样的代码。这就是我发现的。
按钮 otherCamera = (Button) findViewById(R.id.OtherCamera);
otherCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (inPreview) {
camera.stopPreview();
}
//NB: if you don't release the current camera before switching, you app will crash
camera.release();
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);
setCameraDisplayOrientation(CameraActivity.this, currentCameraId, camera);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
如果您想让相机图像以与显示器相同的方向显示,您可以使用它。
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}