Reputation: 77
I want to show a front camera in a layout which is used for only mirror, I want only that and I might have few simple buttons over the camera layout. Note: I don't want to take picture or anything. Just want to show the front camera for mirror. Is there a best way to implement that. I used to try below code but the camera show in wrong rotation similar to landscape mode and the image is stretch.
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
private var mCamera:Camera? = null
override fun surfaceDestroyed(holder: SurfaceHolder) {
mCamera?.stopPreview()
mCamera?.release()
mCamera = null
}
override fun surfaceCreated(holder: SurfaceHolder) {
mCamera = getCameraInstance()
try {
mCamera?.setPreviewDisplay(holder)
} catch (exception: IOException) {
mCamera?.release()
mCamera = null
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int,
height: Int) {
mCamera?.startPreview()
}
})
fun getCameraInstance(): Camera? {
var c: Camera? = null
try {
c = openFrontFacingCamera()
} catch (e: Exception) {
}
return c
}
private fun openFrontFacingCamera(): Camera? {
var cameraCount = 0
var cam: Camera? = null
val cameraInfo = Camera.CameraInfo()
cameraCount = Camera.getNumberOfCameras()
for (camIdx in 0 until cameraCount) {
Camera.getCameraInfo(camIdx, cameraInfo)
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx)
} catch (e: RuntimeException) {
// Log.e(FragmentActivity.TAG, "Camera failed to open: " + e.localizedMessage)
}
}
}
return cam
}
Upvotes: 2
Views: 1424
Reputation: 3261
Following code snippet helped to open front camera
private Camera openFrontFacingCamera() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx<cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Your_TAG", "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam; }
setDisplayOrientation()
method can be used to rotate camera view. Try below code snippet to manage camera orientation.
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);
Upvotes: 1