Last active
July 3, 2024 12:06
-
-
Save e4basil/bff68c089c38e4b1cb6b96529d4f3c3c to your computer and use it in GitHub Desktop.
Auto-focus after X seconds and focus on tap in cameraX :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun View.afterMeasured(crossinline block: () -> Unit) { | |
if (measuredWidth > 0 && measuredHeight > 0) { | |
block() | |
} else { | |
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.GlobalLayoutListener { | |
override fun onGlobalLayout() { | |
if (measuredWidth > 0 && measuredHeight > 0) { | |
viewTreeObserver.removeOnGlobalLayoutListener(this) | |
block() | |
} | |
} | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
previewView.afterMeasured { | |
val autoFocusPoint = SurfaceOrientedMeteringPointFactory(1f, 1f) | |
.createPoint(.5f, .5f) | |
try { | |
val autoFocusAction = FocusMeteringAction.Builder( | |
autoFocusPoint, | |
FocusMeteringAction.FLAG_AF | |
).apply { | |
//start auto-focusing after 2 seconds | |
setAutoCancelDuration(2, TimeUnit.SECONDS) | |
}.build() | |
camera.cameraControl.startFocusAndMetering(autoFocusAction) | |
} catch (e: CameraInfoUnavailableException) { | |
Log.d("ERROR", "cannot access camera", e) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
previewView.afterMeasured { | |
previewView.setOnTouchListener { _, event -> | |
return@setOnTouchListener when (event.action) { | |
MotionEvent.ACTION_DOWN -> { | |
true | |
} | |
MotionEvent.ACTION_UP -> { | |
val factory: MeteringPointFactory = SurfaceOrientedMeteringPointFactory( | |
previewView.width.toFloat(), previewView.height.toFloat() | |
) | |
val autoFocusPoint = factory.createPoint(event.x, event.y) | |
try { | |
camera.cameraControl.startFocusAndMetering( | |
FocusMeteringAction.Builder( | |
autoFocusPoint, | |
FocusMeteringAction.FLAG_AF | |
).apply { | |
//focus only when the user tap the preview | |
disableAutoCancel() | |
}.build() | |
) | |
} catch (e: CameraInfoUnavailableException) { | |
Log.d("ERROR", "cannot access camera", e) | |
} | |
true | |
} | |
else -> false // Unhandled event. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment