Как реализовать масштабирование и предварительный просмотр камеры в KotlinAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как реализовать масштабирование и предварительный просмотр камеры в Kotlin

Сообщение Anonymous »

У меня есть камера, которую я пытаюсь создать в своем приложении, которая позволяет пользователям сжимать экран предварительного просмотра при использовании камеры. Я пытался реализовать масштабирование камеры, но мне совсем не повезло. Это код, который я нашел в теме GitHub
val listener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
// Get the current camera zoom ratio
val currentZoomRatio: Float = cameraInfo.zoomRatio.value ?: 1F

// Get by how much the scale has changed due to the user's pinch gesture
val delta = detector.scaleFactor

// Update the camera's zoom ratio
cameraControl.setZoomRatio(currentZoomRatio * delta)
return true
}
}

val scaleGestureDetector = ScaleGestureDetector(requireContext(), listener)
progressDialog = ProgressDialog(requireContext(), false)
binding.cameraPreview.post {
startCamera()
}
binding.ivImageCapture.setOnClickListener {
progressDialog.show()
takePicture()
}

binding.cameraPreview.setOnTouchListener { _, event ->
scaleGestureDetector.onTouchEvent(event)
return@setOnTouchListener true
}
}

Единственная ошибка — «Неразрешенная ссылка: ZoomRatio». Я обновил все свои зависимости до последней версии.
Вот моя функция startCamera
@SuppressLint("UnsafeExperimentalUsageError")
private fun startCamera() {
// Get screen metrics used to setup camera for full screen resolution
val metrics = DisplayMetrics().also { binding.cameraPreview.display.getRealMetrics(it) }

val screenAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels)

val rotation = binding.cameraPreview.display.rotation

// Bind the CameraProvider to the LifeCycleOwner
val cameraSelector = CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
cameraProviderFuture.addListener({

// CameraProvider
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

// Preview
val preview = Preview.Builder()
.setTargetAspectRatio(screenAspectRatio)
// Set initial target rotation
.setTargetRotation(rotation)

.build()

preview.setSurfaceProvider(binding.cameraPreview.surfaceProvider)

// ImageCapture
imageCapture = initializeImageCapture(screenAspectRatio, rotation)

// ImageAnalysis

cameraProvider.unbindAll()

try { val camera = cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture
)
cameraControl = camera.cameraControl
cameraInfo = camera.cameraInfo
cameraControl.setLinearZoom(0.5f)

} catch (exc: Exception) {
exc.printStackTrace()
}
}, ContextCompat.getMainExecutor(requireContext()))


Подробнее здесь: https://stackoverflow.com/questions/783 ... iew-kotlin
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»