I have a flow with my custom CameraX like this:
- Open camera preview (live)
- Click button to take a photo
- Have a process when clicking that button (convert the path to bitmap, rotated the image, cropping the image automatically, save into device)
- After running all the process and successfully, send the image to other Fragment and display it into a glide
The question is when running all the process (in step 3) have a delayed 2 seconds and the camera preview still live (not freeze or lock). How to make camera preview freeze or lock when running the process?
This is my code to running camera preview in Camera X:
class CameraFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camera, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewFinder.post { setupCamera() }
}
private fun setupCamera() {
CameraX.unbindAll()
CameraX.bindToLifecycle(
this,
buildPreviewUseCase(),
buildImageCaptureUseCase()
)
}
private fun buildPreviewUseCase(): Preview {
val preview = Preview(
UseCaseConfigBuilder.buildPreviewConfig(
viewFinder.display
)
)
preview.setOnPreviewOutputUpdateListener { previewOutput ->
updateViewFinderWithPreview(previewOutput)
correctPreviewOutputForDisplay(previewOutput.textureSize)
}
return preview
}
private fun buildImageCaptureUseCase(): ImageCapture {
val capture = ImageCapture(
UseCaseConfigBuilder.buildImageCaptureConfig(
viewFinder.display
)
)
cameraCaptureImageButton.setOnClickListener {
capture.takePicture(
FileCreator.createTempFile(JPEG_FORMAT),
Executors.newSingleThreadExecutor(),
object : ImageCapture.OnImageSavedListener {
override fun onImageSaved(file: File) {
// I want make a freeze camera preview when execute this before launch *launchGalleryFragment(path)*
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
val rotatedBitmap = bitmap.rotate(90)
val croppedImage = cropImage(rotatedBitmap, viewFinder, rectangle)
val path = saveImage(croppedImage)
requireActivity().runOnUiThread {
launchGalleryFragment(path)
}
}
override fun onError(
imageCaptureError: ImageCapture.ImageCaptureError,
message: String,
cause: Throwable?
) {
Toast.makeText(requireContext(), "Error: $message", Toast.LENGTH_LONG)
.show()
Log.e("CameraFragment", "Capture error $imageCaptureError: $message", cause)
}
})
}
return capture
}
private fun launchGalleryFragment(path: String) {
val action = CameraFragmentDirections.actionLaunchGalleryFragment(path)
findNavController().navigate(action)
}
}