我想照相机屏幕上的一个具体区域。
我在尝试计算和生产照片时认为,我曾尝试过一些图书馆,但我没有做任何工作,因此我需要你的帮助,因为我 st住这个问题,这样做似乎非常容易,但确实不是。
在此,我XML 我照相活动守则:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<androidx.camera.view.PreviewView
android:id="@+id/preview_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/transparentbackground"
android:backgroundTint="#A4686868"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/camera_frame"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="@drawable/ic_camera_frame"
app:layout_constraintBottom_toTopOf="@+id/image_capture_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/preview_view" />
<SeekBar
android:id="@+id/zoom_seek_bar"
android:layout_width="0dp"
android:visibility="gone"
android:layout_height="@dimen/seek_bar_height"
android:layout_marginStart="@dimen/seek_bar_margin"
android:layout_marginEnd="@dimen/seek_bar_margin"
android:layout_marginBottom="@dimen/seek_bar_margin"
app:layout_constraintBottom_toTopOf="@+id/image_capture_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintBottom_toTopOf="@+id/image_capture_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/preview_view">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<Button
android:id="@+id/image_capture_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/capture_btn_end_margin"
android:layout_marginBottom="24dp"
android:elevation="2dp"
android:text="@string/capture"
android:backgroundTint="@color/main"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent" />
<ImageButton
android:id="@+id/closeCamera"
android:layout_width="50dp"
android:layout_height="0dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="24dp"
android:backgroundTint="@color/main"
android:background="@drawable/cross_close_icon"
android:elevation="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ImageButton
android:id="@+id/switchTextInputButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="10dp"
android:layout_marginBottom="24dp"
android:background="@drawable/baseline_text_fields_24"
android:backgroundTint="@color/main"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
并在此附上我的照相活动代码:
class CameraActivity : AppCompatActivity() {
private lateinit var binding: ActivityCameraBinding
private var imageCapture: ImageCapture? = null
private var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
private var counter = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.imageCaptureButton.setOnClickListener {
photoCapture()
}
binding.switchTextInputButton.setOnClickListener {
startActivity(Intent(this@CameraActivity, SensorAddManuelActivity::class.java))
}
if(allPermissionsGrantedByUser()) {
Toast.makeText(this,
"We Have Permission",
Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(
this, Constants.REQUIRED_PERMISSIONS,
Constants.REQUEST_CODE_PERMISSION
)
}
initializeCamera()
cameraCloseButton()
hideSystemNavigationBars()
supportActionBar?.hide()
}
override fun onBackPressed() {
counter++
if (counter == 1){
val intent = Intent(this, OpenCameraActivity::class.java)
startActivity(intent)
}
}
private fun hideSystemNavigationBars() {
window.decorView.apply {
systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == Constants.REQUEST_CODE_PERMISSION){
if(allPermissionsGrantedByUser()){
initializeCamera()
}else{
Toast.makeText(this,
"Permissions not granted by the user.",
Toast.LENGTH_SHORT).show()
finish()
}
}
}
private fun allPermissionsGrantedByUser() =
Constants.REQUIRED_PERMISSIONS.all{
ContextCompat.checkSelfPermission(
baseContext, it
) == PackageManager.PERMISSION_GRANTED
}
private fun cameraCloseButton() {
binding.closeCamera.setOnClickListener{
startActivity(Intent(this@CameraActivity, OpenCameraActivity::class.java))
}
}
private fun photoCapture() {
imageCapture ?: return
val photoFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), SimpleDateFormat("yyyyMMddHHmmSS", Locale.US).format(System.currentTimeMillis()) + ".jpeg")
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture!!.takePicture(
outputOptions, ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
try {
val savedUri = Uri.fromFile(photoFile)
savedUri.path?.let { safePath ->
val file = File(safePath)
file.delete()
}
} catch (e: Exception) {
e.printStackTrace()
}
Toast.makeText(
this@CameraActivity,
"Something went wrong!",
Toast.LENGTH_LONG
).show()
}
@SuppressLint("RestrictedApi")
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
savedUri.path?.let { safePath ->
CameraPreviewActivity.path = safePath
startActivity(Intent(this@CameraActivity, CameraPreviewActivity::class.java))
}
}
}
)
}
private fun initializeCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(binding.previewView.surfaceProvider)
}
imageCapture = ImageCapture.Builder()
.build()
try {
cameraProvider.unbindAll()
val camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
val cameraControl = camera.cameraControl
val cameraInfo = camera.cameraInfo
cameraTouchControls(cameraControl, cameraInfo)
sliderBarZoomFeature(cameraControl)
} catch(e: Exception) {
e.printStackTrace()
}
}, ContextCompat.getMainExecutor(this))
}
private fun cameraTouchControls(cameraControl: CameraControl, cameraInfo: CameraInfo) {
val listener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
val currentZoomRatio = cameraInfo.zoomState.value?.zoomRatio ?: 0F
binding.zoomSeekBar.progress = currentZoomRatio.toInt()
val delta = detector.scaleFactor
cameraControl.setZoomRatio(currentZoomRatio * delta)
return true
}
}
val scaleGestureDetector = ScaleGestureDetector(baseContext, listener)
binding.previewView.setOnTouchListener { _, event ->
scaleGestureDetector.onTouchEvent(event)
if (event.action == MotionEvent.ACTION_DOWN) {
val factory = binding.previewView.meteringPointFactory
val point = factory.createPoint(event.x, event.y)
val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
.setAutoCancelDuration(5, TimeUnit.SECONDS)
.build()
cameraControl.startFocusAndMetering(action)
}
true
}
}
private fun sliderBarZoomFeature(cameraControl: CameraControl) {
val zoomSlider = findViewById<SeekBar>(R.id.zoom_seek_bar)
zoomSlider.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
cameraControl.setLinearZoom(progress / 100.toFloat())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
}
}