Draw Circle in Preview in CameraX describing TapToFocus

1.3k views Asked by At

I am trying to implement TapToFocus feature using the CameraX Api .I have implemented it successfully but not able to know how to draw a circle on the preview describing the Location pressed by the user .

I want to have a circle in the preview like the image has

1

There are 1 answers

2
Husayn Hakeem On BEST ANSWER

The are many ways to draw and animate a focus ring around a tap position on PreviewView, some fancier than others. One simple way of doing so is to:

  1. Create a Drawable of the ring, something like this for instance.

  2. Layout an ImageView containing the Drawable on top of PreviewView, and initially hide it.

<FrameLayout ...>

    <androidx.camera.view.PreviewView
        ... />

    <ImageView
        android:id="@+id/focusRing"
        android:src="@drawable/focus_ring"
        android:visibility="invisible"
        ... />

</FrameLayout>
  1. Set up a touch listener on PreviewView. On a touch event, use the event's coordinates to show the ring around it.
private void animateFocusRing(float x, float y) {
    ImageView focusRing = findViewById(R.id.focusRing);

    // Move the focus ring so that its center is at the tap location (x, y)
    float width = focusRing.getWidth();
    float height = focusRing.getHeight();
    focusRing.setX(x - width / 2);
    focusRing.setY(y - height / 2);

    // Show focus ring
    focusRing.setVisibility(View.VISIBLE);
    focusRing.setAlpha(1F);

    // Animate the focus ring to disappear
    focusRing.animate()
        .setStartDelay(500)
        .setDuration(300)
        .alpha(0F)
        .setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animator) {
                focusRing.setVisibility(View.INVISIBLE);
            }

            // The rest of AnimatorListener's methods.
        });
}