У меня есть камера, которую я пытаюсь создать в своем приложении, которая позволяет пользователям сжимать экран предварительного просмотра при использовании камеры. Я пытался реализовать масштабирование камеры, но мне совсем не повезло. Это код, который я нашел в теме 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
Как реализовать масштабирование и предварительный просмотр камеры в Kotlin ⇐ Android
Форум для тех, кто программирует под Android
1713275430
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». Я обновил все свои зависимости до последней версии.
[b]Вот моя функция startCamera[/b]
@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()))
Подробнее здесь: [url]https://stackoverflow.com/questions/78330383/how-to-implement-pinch-to-zoom-and-camera-preview-kotlin[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия