在今年的Google I/O大會上,Google新推出了CameraX支持包,按照官方的說法, 這個包的做用是php
help you make camera app development easierandroid
google在幾年前推出了Camera2 API用於取代Camera1, 大部分開發者仍是喜歡使用Camera1的api,一是由於api太難用,二是要兼容5.0以前的s設備,此次推出的CameraX支持包不只消除各類使用上的障礙,還與大受好評的archecture component 包的Lifecycle結合,自動管理相機的生命週期,開發者不在須要去關心何時打開相機,何時釋放相機。甚至聯繫各個手機廠商提供統一的api調用使用美顏等接口。git
關於cameraX的介紹本文不在贅述,將使用cameraX實現一個小功能:使用最少的代碼實現二維碼解碼,在這個demo中將會使用到CameraX中三大功能中的兩個:github
建立app,聲明相機權限api
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="github.hotstu.camerax.qrcodec">
<uses-permission android:name="android.permission.CAMERA"/>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
複製代碼
添加相關依賴app
implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.5'
def camerax_version = "1.0.0-alpha02"
implementation "androidx.camera:camera-core:${camerax_version}"
// If you want to use Camera2 extensions.
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation 'com.google.zxing:core:3.3.2'
複製代碼
注意,這裏有個坑, 由於camerax尚未發佈正式版,而它依賴的androidx.core:core:1.1.0-rc1
中AppcompatActivity
竟然不是LifeCycleOwner
,,然而camerax依賴LifeCycleOwner
才能管理生命週期,因此要祭出在support liabary時代解決依賴衝突的黃金代碼:ide
subprojects {
configurations.all {
resolutionStrategy {
force "androidx.core:core:1.0.2"
}
}
}
複製代碼
val previewConfig = PreviewConfig.Builder().apply {
setTargetAspectRatio(Rational(1, 1))
setTargetResolution(Size(640, 640))
}.build()
val preview = Preview(previewConfig)
preview.setOnPreviewOutputUpdateListener {
textureView.surfaceTexture = it.surfaceTexture
}
CameraX.bindToLifecycle(this@MainActivity, preview)
複製代碼
數據分析能夠指定回調的線程oop
val analysisConfig = ImageAnalysisConfig.Builder().apply {
setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
val analyzerThread = HandlerThread("BarcodeAnalyzer").apply { start() }
setCallbackHandler(Handler(analyzerThread.looper))
}.build()
val analysis = ImageAnalysis(analysisConfig)
analysis.analyzer = QRcodeAnalyzer()
CameraX.bindToLifecycle(this@MainActivity, analysis)
複製代碼
class MainActivity : AppCompatActivity() {
@SuppressLint("CheckResult")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val previewConfig = PreviewConfig.Builder().apply {
setTargetAspectRatio(Rational(1, 1))
setTargetResolution(Size(640, 640))
}.build()
val analysisConfig = ImageAnalysisConfig.Builder().apply {
setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
val analyzerThread = HandlerThread("BarcodeAnalyzer").apply { start() }
setCallbackHandler(Handler(analyzerThread.looper))
}.build()
val rxPermissions = RxPermissions(this)
val preview = Preview(previewConfig)
val analysis = ImageAnalysis(analysisConfig)
preview.setOnPreviewOutputUpdateListener {
textureView.surfaceTexture = it.surfaceTexture
}
analysis.analyzer = QRcodeAnalyzer()
rxPermissions.request(android.Manifest.permission.CAMERA)
.subscribe {
CameraX.bindToLifecycle(this@MainActivity,
preview,
analysis)
}
}
}
複製代碼
作二維碼解碼,不少開發者是直接在zxing-Android 項目基礎上刪刪改改,其實不建議這樣作,應爲那個項目是從Android早期版本開始的,一些東西都爲了支持老版本系統而作出了妥協,不少代碼都顯得老舊並且不優雅,查看源碼你會發現它調用攝像頭的方法是很是複雜的。這裏咱們只是用xzing核心庫com.google.zxing:core
ui
class QRcodeAnalyzer : ImageAnalysis.Analyzer {
private val reader: MultiFormatReader = MultiFormatReader()
init {
val map = mapOf<DecodeHintType, Collection<BarcodeFormat>>(
Pair(DecodeHintType.POSSIBLE_FORMATS, arrayListOf(BarcodeFormat.QR_CODE))
)
reader.setHints(map)
}
override fun analyze(image: ImageProxy, rotationDegrees: Int) {
if (ImageFormat.YUV_420_888 != image.format) {
Log.e("BarcodeAnalyzer", "expect YUV_420_888, now = ${image.format}")
return
}
val buffer = image.planes[0].buffer
val data = ByteArray(buffer.remaining())
val height = image.height
val width = image.width
buffer.get(data)
//TODO 調整crop的矩形區域,目前是全屏(全屏有更好的識別體驗,可是在部分手機上可能OOM)
val source = PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false)
val bitmap = BinaryBitmap(HybridBinarizer(source))
try {
val result = reader.decode(bitmap)
Log.e("BarcodeAnalyzer", "resolved!!! = $result")
} catch (e: Exception) {
Log.d("BarcodeAnalyzer", "Error decoding barcode")
}
}
}
複製代碼
大功告成, 核心代碼不超過100行。this
總結一下,目前cameraX還在有待完善,例如處理攝像頭的rotation的時候仍是很是迷。
本人在掘金上寫的內容除特別註明之外均爲本人原創,轉載需經本人贊成,歡迎轉載分享,請註明出處。