Skip to content

Commit

Permalink
Merge pull request #817 from minvws/allow-user-focus-camera
Browse files Browse the repository at this point in the history
Allow user focus camera
  • Loading branch information
BartNijland91 authored Nov 3, 2021
2 parents 90290ee + d7d27bf commit c5f9708
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package nl.rijksoverheid.ctr.qrscanner

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.ViewTreeObserver
import androidx.camera.core.*
import androidx.camera.view.PreviewView
import timber.log.Timber

fun PreviewView.focusOnTouch(cameraControl: CameraControl) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
@SuppressLint("ClickableViewAccessibility")
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)

setOnTouchListener { _, event ->
return@setOnTouchListener when (event.action) {
MotionEvent.ACTION_DOWN -> {
true
}
MotionEvent.ACTION_UP -> {
val factory: MeteringPointFactory = SurfaceOrientedMeteringPointFactory(
width.toFloat(), height.toFloat()
)
val autoFocusPoint = factory.createPoint(event.x, event.y)
try {
cameraControl.startFocusAndMetering(
FocusMeteringAction.Builder(
autoFocusPoint,
FocusMeteringAction.FLAG_AF
).apply {
// focus only when the user taps the preview
disableAutoCancel()
}.build()
)
} catch (e: CameraInfoUnavailableException) {
Timber.d("ERROR", "cannot access camera", e)
}
true
}
else -> false // Unhandled event.
}
}
}
}
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import android.content.pm.PackageManager
import android.graphics.Paint
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
Expand Down Expand Up @@ -224,6 +226,11 @@ abstract class QrCodeScannerFragment : Fragment(R.layout.fragment_scanner) {
cameraSelector,
cameraPreview
).also { camera ->
try {
previewView.focusOnTouch(camera.cameraControl)
} catch (exception: Exception) {
Timber.e(exception)
}
// If device supports flash, enable flash functionality
if (camera.cameraInfo.hasFlashUnit()) {
binding.toolbar.menu.findItem(R.id.flash)?.let { flashItem ->
Expand Down

0 comments on commit c5f9708

Please sign in to comment.