问题描述
Android在最近几个月中发布了新的API camerax.我正在尝试了解如何使相机自动对焦.
Android has released a new API camerax in recent months. I'm trying to understand how to get auto-focusing for the camera to work.
https://groups.google.com/a/android.com/forum/#!searchin/camerax-developers/auto $ 20focus | sort:date/camerax-developers/IQ3KZd8iOIY/LIbrRIqEBgAJ
https://groups.google.com/a/android.com/forum/#!searchin/camerax-developers/auto$20focus|sort:date/camerax-developers/IQ3KZd8iOIY/LIbrRIqEBgAJ
这里是关于该主题的讨论,但是几乎没有特定的文档.
Here is a discussion on the topic but there is almost no specific documentation on it.
这也是基本的camerax应用,但我找不到任何与自动对焦有关的文件.
Here is also the basic camerax app but I couldn't find any file dealing with the auto focusing.
任何有关文档的提示或技巧都是有帮助的.另外,我对android还是很陌生,所以很可能会丢失一些使上面的链接更有用的东西.
Any tips or points to documentation is helpful. Also I'm fairly new to android so its very possible I'm missing something that makes the above links more useful.
推荐答案
使用当前的CameraX 1.0.0-rc02&1.0.0-alpha21
工件,您可以通过以下两种方式进行操作:
With the current CameraX 1.0.0-rc02 & 1.0.0-alpha21
artifacts, you can proceed in this 2 ways:
-
每X秒自动对焦:
Auto-focus every X seconds:
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)
}
}
轻按一下即可
Focus on-tap:
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.
}
}
}
afterMeasured 扩展功能是一个简单的实用程序:
afterMeasured extension function is a simple utility:
inline fun View.afterMeasured(crossinline block: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
block()
}
}
})
}
可以使用
Camera 对象获取
val camera = cameraProvider.bindToLifecycle(
this@Activity, cameraSelector, previewView //this is a PreviewView
)
这篇关于如何使用Android CameraX自动对焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!