我正在使用 androidx 组件中的 CameraView ,当我使用 takePicutre 方法时,大约需要2秒钟在 ImageCapture.OnImageSavedListener 侦听器中调用 onImageSaved 方法,这会使用户感觉好像出了点问题。
这是我的代码:
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秒,我想是因为lifecyclerOwner对象,但是我不知道在哪里我应该把bind方法放到什么地方,并准确地取消绑定。
所以我有两个问题
1-为什么相机视图要花费太多时间来捕获微微图片,以及如何减少此时间?
2-为什么在使用 Fragment 时调用 takePicutre 方法后出现黑屏?