azabaluev
azabaluev

Reputation: 41

How to show camera focus rectangle with Android CameraX

I use android camerax in my app.

The focus-on-tap is implemented as in this answer: https://stackoverflow.com/a/60095886/978067

            cameraPreview.setOnTouchListener((view, event)  -> {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        return true;
                    case MotionEvent.ACTION_UP:
                        MeteringPoint point = cameraPreview.getMeteringPointFactory().createPoint(event.getX(), event.getY());
                        FocusMeteringAction action = new FocusMeteringAction.Builder(point).build();
                        camera.getCameraControl().startFocusAndMetering(action);

                        // HOW TO SHOW RECTANGLE SIGHT HERE? Thanx!

                        return true;
                    default:
                        return false;
                }
            });

But I need to show rectangle sight around focus point (as in standard camera app)

Have any ideas how to do it?

Upvotes: 0

Views: 2567

Answers (2)

Deepu George Jacob
Deepu George Jacob

Reputation: 474

Your cameraProvider.bindToLifecycle will return camera object. Use the method like below to focus specific region.

private fun cameraFocusPoint(camera: Camera, regionWidth:Float,regionHeight:Float) {

    val meteringPointFactory = SurfaceOrientedMeteringPointFactory(
        regionWidth,
        regionHeight
    )
    val autoFocusPoint =
        meteringPointFactory.createPoint((regionWidth / 2),
            ( regionHeight / 2)
        )
    camera.cameraControl.startFocusAndMetering(
        FocusMeteringAction.Builder(autoFocusPoint).build()

}

Upvotes: 1

Raz Leshem
Raz Leshem

Reputation: 201

Using CameraX the tap to focus is done using the touch point - x, y coordinates. You can set the focus rectangle x and y as the motion event x and y. The focus rectangle should be a custom view that you can create.

/** Represents the x coordinate of the tap event */
val x = motionEvent.x
/** Represents the y coordinate of the tap event */
val y = motionEvent.y
// Setting the focus rectangle view x coordinate as the motion event x coordinate
focusRectangleView.x = x
// Setting the focus rectangle view y coordinate as the motion event y coordinate
focusRectangleView.y = y

This is how you can show the focus rectangle view where the tap occurred, and also simply change the view visibility whenever you want to show it or hide it.

Upvotes: 2

Related Questions