0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

カメラの起動方法

Posted at

ScanContract ScanOptionsCameraSettingsでカメラを起動する方法の違いについてメモします。

ScanContract はActivity Result APIでコードスキャン後の処理を記述するためのContractです。ScanOptions は、そのスキャンに関する設定を決めることができます。

2つを組み合わせることで、簡単にカメラを起動してコードだけを読み取ることができることが特徴です。
・カメラ操作はすべてライブラリ側が自動で管理する
・コードを読み取ったあとは画面は自動で閉じる
・フラッシュ、ズームなど細かいカメラ設定はできない

val scanQrResultLauncher = registerForActivityResult(ScanContract()) { result ->
    if (result.contents != null) {
        // 読み取った後の処理
    }
}

val options = ScanOptions().apply {
    setDesiredBarcodeFormats(ScanOptions.QR_CODE)
    setPrompt("コードをスキャンしてください")
}
scanQrResultLauncher.launch(options)

CameraSettingsはカメラの細かい設定を直接制御できます。DecoratedBarcodeViewなどのカスタムビューと組み合わせて使います。
レイアウトにカメラビューを埋め込めてそれに対してオートフォーカス、フラッシュ制御などの細かいカスタマイズが可能です。カメラビューを自由にカスタマイズしたい場合や、読み取り後に画面遷移させたくない場合に使用します。実装の手間はその分増えます。

<com.journeyapps.barcodescanner.DecoratedBarcodeView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/barcodeView"/>
override fun onCreate(savedInstanceState: Bundle?) {
    val cameraSettings = CameraSettings().apply {
        requestedCameraId = CameraSettings.CameraFacing.BACK
        isAutoFocusEnabled = true
    }

    binding.barcodeView.barcodeView.cameraSettings = cameraSettings

    val formats = listOf(BarcodeFormat.QR_CODE)
    binding.barcodeView.barcodeView.decoderFactory = DefaultDecoderFactory(formats)
}

override fun onResume() {
    super.onResume()
    binding.barcodeView.resume()
}

override fun onPause() {
    super.onPause()
    binding.barcodeView.pause()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?