我正在使用androidx组件中的CameraView,当我使用takePicutre方法时,在ImageCapture.OnImageSavedListener监听器中调用onImageSaved方法大约需要2秒,这让用户感觉有问题。
这是我的代码:
private fun takePicture() {
Log.d("ThreadRunning", Thread.currentThread().name)
val file = File(filesDir, UUID.randomUUID().toString())
val executor = Executors.newSingleThreadExecutor()
val startTime = System.currentTimeMillis()
cameraView?.takePicture(file, executor,
object : ImageCapture.OnImageSavedListener {
override fun onError(
error: ImageCapture.ImageCaptureError,
message: String,
exc: Throwable?
) {
runOnUiThread {
captureButton.visibility = View.VISIBLE
cameraView.visibility = View.VISIBLE
}
Log.d("CaptureClicked", "{$message}")
}
override fun onImageSaved(file: File) {
val bmOptions = BitmapFactory.Options()
var bitmap = BitmapFactory.decodeFile(file.absolutePath, bmOptions)
val displayMetrics = DisplayMetrics()
windowManager?.defaultDisplay?.getMetrics(displayMetrics)
//val width = displayMetrics.widthPixels
//val height = displayMetrics.heightPixels
val width = cameraView.width
val height = cameraView.height
val numratorValue = (height.toDouble() / width.toDouble()).roundToInt()
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true)
bitmap = if (cameraView.cameraLensFacing == CameraX.LensFacing.FRONT) {
bitmap.rotate(270F).mirror()
} else {
bitmap.rotate(90F)
}
runOnUiThread{
capturedImageView.setImageBitmap(bitmap)
capturedImageView.visibility = View.VISIBLE
cancelButton.visibility = View.VISIBLE
captureButton.visibility = View.INVISIBLE
}
Log.d("TestDelay", "${System.currentTimeMillis() - startTime}")
}
}
)
}
private fun Bitmap.rotate(degrees: Float): Bitmap {
val matrix = Matrix().apply {
postRotate(degrees)
}
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
private fun Bitmap.mirror(): Bitmap {
val matrix = Matrix().apply {
preScale(-1F, 1F)
}
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
这是cameraView的xml元素
<androidx.camera.view.CameraView
android:id="@+id/cameraView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:captureMode="image"/>
另一个问题,当我在Fragment中使用takePicture方法时,我得到了 0.5 秒的黑屏,我认为是因为生命周期管理器对象,但我不知道应该将绑定方法放在哪里以及在哪里取消绑定。
所以我有两个问题
1 - 为什么相机视图需要太多时间来捕捉图片以及如何减少这个时间?
2 - 为什么我在使用Fragment时调用takePicutre方法后会出现黑屏?